2013-02-19 5 views
4

나는 스프라이트가있는 플레이어 클래스가 있으며 마우스 포인터를 향하게하고 싶습니다. 나는 스프라이트의 회전이해야 무엇을 작동하려면이 옵션을 사용하고캔버스 요소에 스프라이트 회전하기

: 내 Player 클래스의 내 그리기 방법 다음

this.rotation = -(Math.atan2(this.x - mouseState.x, this.y - mouseState.y) * 180/Math.PI); 

와 나는이 일을 해요 :

Player.prototype.draw = function() { 
    window.ctx.save(); 
    window.ctx.translate(this.x + this.sprite.width/2, this.y + this.sprite/height/2); 
    window.ctx.rotate(this.rotation); 
    window.ctx.drawImage(this.sprite, this.x, this.y); 
    window.ctx.restore(); 
} 

하지만 내가 원하는 것은 아닙니다. 스프라이트는 캔버스의 왼쪽 상단 주위에있는 원에서 거칠게 움직이는 것처럼 보입니다 (x:0, y:0).

스프라이트의 중심을 마우스 커서를 기준으로 원점으로 사용하려면 어떻게해야합니까?

답변

1

번역 할 필요가 없습니다. 아래에 추가 된 window.ctx.translate 호출을주의 깊게 살펴보고 x 값과 y 값에 모두 음수를 추가하는 방법에 유의하십시오. 기본적으로

Player.prototype.draw = function() { 
    window.ctx.save(); 
    window.ctx.translate(this.x + this.sprite.width/2, this.y + this.sprite/height/2); 
    window.ctx.rotate(this.rotation); 
    window.ctx.translate(-this.x + this.sprite.width/2, -this.y + this.sprite/height/2); 
    window.ctx.drawImage(this.sprite, this.x, this.y); 
    window.ctx.restore(); 
} 

, 무슨이 (회전)을 회전 개체 센터 (번역) 캔버스 컨텍스트 중심을 이동하고있다, 당신은 당신이에서 그것을 가지고 있었다에서 다시 중심점을 이동해야합니다.

0

Math.atan2 (Y, X)을 y 인수 제 온다

참고 다음x. 논쟁을 돌리십시오.

또한 값을 라디안 단위로 반환하며 Math.atan2(1,0)을 호출하면 알 수 있습니다. 변환을 도수로 제거하십시오.

이것은 당신의 RAD-℃, 변환을하지 않으려는 다시 라디안

의미로 측정 시계 방향 회전입니다.

this.rotation = Math.atan2(this.y-mouseState.y, this.x-mouseState.x); 

window.ctx.rotate(this.rotation); 
+0

스프라이트는 각도로 변환하지 않아서 너무 거칠게 회전하지 않지만 캔버스의 왼쪽 상단 주위에 큰 원으로 회전합니다. –

+0

먼저 'rotate'하고 * 다음에'translate '해야합니다. –

관련 문제