2013-02-14 71 views
0

我試圖讓我的對象始終面對我的玩家,但我正在努力與它背後的數學。到目前爲止,我的對象確實在我的球員移動的位置旋轉,但它不一致。HTML5 JavaScript - 旋轉對象面對目標

這是我用我的旋轉對象:

var targetX = player.x - this.width/2; 
var targetY = player.y - this.height/2; 

this.rotation = Math.atan2(targetY, targetX); 
ctx.transform(1, 0, 0, 1, this.x, this.y); 

//ART WORK 
ctx.save() 
    ctx.translate(15, 15); 
    ctx.rotate(this.rotation); 

    ctx.fillStyle = "866c4a"; 
    ctx.fillRect(-15, -15, this.width, this.height); 
ctx.restore(); 

就像我說的,它不能正常工作,我相信這是我的數學做。

謝謝

回答

0

好吧!

我立即發現問題是什麼。我沒有考慮到對象的位置:

var targetX = player.x - this.x; 
var targetY = player.y - this.y; 

this.rotation = Math.atan2(targetY, targetX); 
ctx.transform(1, 0, 0, 1, this.x, this.y); 

//ART WORK 
ctx.save() 
    ctx.translate(15, 15); 
    ctx.rotate(this.rotation); 

    ctx.fillStyle = "866c4a"; 
    ctx.fillRect(-15, -15, this.width, this.height); 
ctx.restore(); 

我會離開這個QnA,因爲別人會遇到這個問題。 :)