2012-05-20 49 views
0

我有一個移動罐:http://www.exeneva.com/html5/movingTankExample/爲什麼我的坦克不能正確旋轉?

罐使用有限狀態機,用於它面對的方向,採用默認設置爲「向上」:

var tankDir = "up"; 

處理該旋轉的功能是以下:

function dirTank(dir) { 
    switch (dir) { 
    case "up": 
     if (tankDir == "right") { 
     rotationAngle += -90; 
     } else if (tankDir == "down") { 
     rotationAngle += 180; 
     } else if (tankDir == "left") { 
     rotationAngle += 90; 
     } 
     break; 
    case "down": 
     if (tankDir == "up") { 
     rotationAngle += 180; 
     } else if (tankDir == "right") { 
     rotationAngle += 90; 
     } else if (tankDir == "left") { 
     rotationAngle += -90; 
     } 
     break; 
    case "left": 
     if (tankDir == "up") { 
     rotationAngle += -90; 
     } else if (tankDir == "right") { 
     rotationAngle += 180; 
     } else if (tankDir == "down") { 
     rotationAngle += 90; 
     } 
     break; 
    case "right": 
     if (tankDir == "up") { 
     rotationAngle += 90; 
     } else if (tankDir == "down") { 
     rotationAngle += -90; 
     } else if (tankDir == "left") { 
     rotationAngle += 180; 
     } 
     break; 
    } 
    tankDir = dir; 
    rotationAngle %= 360; 
} 

在drawScreen坦克渲染代碼如下所示:

// Draw the tank 
    context.save(); 
    context.setTransform(1,0,0,1,0,0); // identity matrix 
    context.translate(tankX + tileWidth/2, tankY + tileHeight/2); 
    rotationAngle = rotationAngle * Math.PI/180; 
    context.rotate(rotationAngle); 
    context.drawImage(tileSheet, tankSourceX, tankSourceY, tileWidth, tileHeight, -tileWidth/2, -tileHeight/2, tileWidth, tileHeight); 
    context.restore(); 

但坦克似乎轉動,然後突然恢復到原來的方向。有人可以幫我解決這個問題嗎?

+1

這段代碼看起來並不是問題所在。 –

+0

你的坦克有點難以控制 – 2012-05-20 05:02:05

+0

@Webtecher如何? –

回答

2

rotationAngle應該保存在另一個變量中,並且您的所有分配都應該更改爲增加或減少當前角度。

rotationAngle += 90; // turn right 
rotationAngle += 180; // reverse direction 

這些更改後,需要規範化的角度:

rotationAngle %= 360; 

更新

Make sure to not overwrite the `rotationAngle` later in the code when you convert from degrees to radians. 

rotationAngle = rotationAngle * Math.PI/180; 

應該改爲:

rotationAngleRad = rotationAngle * Math.PI/180; 

然後在.rotate()調用中使用rotationAngleRad

+0

已更新,但仍未完全正常工作。 –

+0

@YangPulse這是什麼意思?你在看什麼? –

+0

我根據您的意見更新了代碼,但我看到的是我所看到的同樣的事情。 –

1

原因是每次重繪畫布時都需要改變旋轉角度,而不僅僅是第一次。

+0

我做到了。檢查上面的代碼。 –

+0

@YangPulse在你的超時期間被調用的drawScreen函數期間怎麼樣? – qw3n

+0

啊,那就是它的位置。任何想法如何解決它? –