VSt*_*ate 1 javascript math canvas angle rotation
我这里有一个小提琴。我要问的是太空船必须面向运动的方向,因为不这样做是没有意义的。无论如何,我认为我遇到的问题是找到一个角度,并在船以不同方式移动时让船旋转该角度。
function draw () { //Create and animates
var angle = Math.atan2(clickedChords.y - player.y, clickedChords.x - player.x);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle= 'white';
ctx.beginPath();
//Creates crossHair/nav marker
ctx.arc(clickedChords.x,clickedChords.y,3,0,360);
ctx.rect(clickedChords.x - 8,clickedChords.y - 1,16,2);
ctx.fill();
ctx.drawImage(ships.blueBeginers,player.x-15,player.y-15);
player.x += Math.cos(angle);
player.y += Math.sin(angle);
requestAnimationFrame(draw); //God
}
draw();
Run Code Online (Sandbox Code Playgroud)
我在翻译图像然后从图像中间旋转时遇到问题。这可能很简单,但我被卡住了。
感谢你们对我的帮助。
小智 5
在代码中,它将是这些行:
ctx.translate(player.x, player.y); // translate to center of rotation
ctx.rotate(angle + 0.5*Math.PI); // rotate, here +90deg to comp image dir.
ctx.translate(-player.x, -player.y); // translate back
ctx.drawImage(ships.blueBeginers,player.x-15,player.y-15); // draw image
ctx.setTransform(1,0,0,1,0,0); // reset transforms (identity matrix)
Run Code Online (Sandbox Code Playgroud)
闪烁是因为您计算了每帧的 atan2 角度。当位置等于点击位置时,由于稍后添加 cos/sin,您将有一个非常小的值切换的 atan。
您可以通过在此版本中缓存单击对象上的角度来解决此问题:
但是,您需要进行条件检查才能停止动画,因为现在您只需添加 cos/sin 中的值,并没有阻止它(这是一种方法)。
提示 1:创建面向右侧的船舶图像。这将对应于 0°,从而避免每次添加 90°。
技巧 2:将角度值和计算缓存一次,您就不必每次都计算 atan2/cos/sin,因为它们是相对昂贵的操作。
| 归档时间: |
|
| 查看次数: |
942 次 |
| 最近记录: |