2013-02-19 115 views
4

我有一個精靈的玩家類,我想讓它面向我的鼠標指針。旋轉畫布元素上的精靈

我用這個工作了精靈的轉動應該是什麼:

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

,然後在我的Player類的我的畫法我這樣做:

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),您會知道該值。刪除轉換爲度數。

這是弧度

含義測量順時針旋轉,再次,你不希望你的抗輻射度的轉換。

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

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

由於沒有將其轉換爲度數,精靈旋轉並不那麼瘋狂,但它仍然圍繞畫布左上角的大圓圈旋轉。 – 2013-02-19 00:47:56

+0

您需要首先旋轉,然後*翻譯。 – 2013-02-19 01:46:34