javascript 조이스틱 구현 및 회전속도 값 구하기

vue.js로 조이스틱 로직을 구현 후 해결할 문제 발생

구현

조건

먼저 생각을 한건 아래와 같았다.

원의 중점을 기준으로 minSpeed, maxSpeed 도출

원의 중점을 기준으로 12시(90deg) , 3시 (0deg) , 6시(-90), 9시 (180deg, -180deg)

해당 각도를 통하여 아래와 같은 기대값을 도출하기위해 매핑값 정리

  1. 0~+-180 입력 범위에서 왼쪽/오른쪽/위/아래 구분필요(전진, 후진 구분 및 회전 방향 구분)
  2. 0~+-180 입력 범위를 360도기준 4분면으로 0~90도 변환필요.
  3. 0~90도 각도값을 속도로 변환

최종 회전속도값 = (회전 방향 구분한 값) * 최대속도 * (2단계에서 변환한 각도값 / 90도 -> 1도에 대한 변환값 필요)

코드의 일부분은 아래와 같다.

const offset = 128 - 32
const radians = Math.atan2(y, x)
const angle = Math.round((radians * 180) / Math.PI, 4)

this.angle = -1 * angle

if (Math.abs(this.angle) > 90) {
    this.angle = Math.abs(this.angle) - 180
} else {
    this.angle = Math.abs(this.angle)
}

 // console.log((회전 방향 구분한값) * 최대속도 * this.angle / 90)

if (this.y < 0) {
    this.direction = 'front'
}

if (this.y >= 0) {
    this.direction = 'back'
}

this.speed = Math.min(
    Math.round(Math.sqrt(Math.pow(y, 2) + Math.pow(x, 2))),
    100,
)
this.x = this.speed > offset ? Math.cos(radians) * offset : x
this.y = this.speed >= offset ? Math.sin(radians) * offset : y

위와 같은 매핑을 통한 문제 도출로 회전속도값 만들게됨.

Leave a Comment