如何旋转rect,并且它仍然根据其旋转沿正确的方向移动

how to rotate a rect and it still move in the right direction based on its rotation

本文关键字:旋转 移动 方向 何旋转 rect      更新时间:2023-12-15

我正在用HTML5/JavaScript制作一个游戏,我希望玩家旋转,并根据其旋转向正确的方向移动。这里有一个链接,我得到了基本的旋转:HTML5画布-旋转对象而不移动坐标。这是我的一些代码:

<canvas id="canvas" width="500" height="500" style="border: 1px solid #000;"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var keys = [];
window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e){
delete keys[e.keyCode];
}, false);
var player = {
x: 10,
y: 10,
width: 15,
height: 15,
color: 'blue',
speed: 3,
rotate: 0,
rotateSpeed: 2
};
function game(){
update();
render();
}
function update(){
if(keys[87] || keys[38]) player.y -= player.speed;
if(keys[83] || keys[40]) player.y += player.speed;
if(keys[65] || keys[37]) player.rotate += player.rotateSpeed;
if(keys[68] || keys[39]) player.rotate -= player.rotateSpeed;
}
function render(){
ctx.clearRect(0,0,WIDTH,HEIGHT);
ctx.save();
ctx.translate(player.x+player.width/2, player.y+player.height/2);
ctx.rotate(player.rotate*Math.PI/180);
renderObject(-player.width/2, -player.height/2, player.width, player.height, player.color);
ctx.restore();
}
function renderObject(x,y,width,height,color){
ctx.fillStyle = color;
ctx.fillRect(x,y,width,height);
}
setInterval(function(){
game();
}, 25);
</script>

播放器只是在屏幕上上上下移动,但我希望它朝着它所面对的方向移动。

当你调整速度时,你需要考虑球员的角度。试试类似的东西:

function update() {
    if(keys[87] || keys[38]) {
        player.y -= Math.cos(player.rotate*Math.PI/180) * player.speed;
        player.x -= Math.sin(player.rotate*Math.PI/180) * player.speed;
    }
    if(keys[83] || keys[40]) {
        player.y += Math.cos(player.rotate*Math.PI/180) * player.speed;
        player.x += Math.sin(player.rotate*Math.PI/180) * player.speed;
    }
    if(keys[65] || keys[37]) player.rotate += player.rotateSpeed;
    if(keys[68] || keys[39]) player.rotate -= player.rotateSpeed;
}

cos()和sin()是三元函数,以弧度为参数。因此得出了Math.PI/180的转换因子。

希望这能奏效。我在平板电脑上,在这里无法轻松测试。。。