【问题标题】:how to rotate a rect and it still move in the right direction based on its rotation如何旋转一个矩形,它仍然根据它的旋转向正确的方向移动
【发布时间】:2016-07-22 17:13:25
【问题描述】:

我正在使用 HTML5/JavaScript 制作游戏,我希望玩家旋转,并根据其旋转向正确的方向移动。这是我获得基本轮换的链接:HTML5 canvas - rotate object without moving coordinates。这是我的一些代码:

<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>

玩家只是在屏幕上上下移动,但我希望它朝其面对的方向移动。

【问题讨论】:

    标签: javascript html rotation


    【解决方案1】:

    您需要在调整速度时考虑玩家的角度。尝试类似:

    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 的转换因子。

    希望这能解决问题。我在平板电脑上,无法从这里轻松测试...

    【讨论】:

    • 感谢它的工作,除了一件事。当我旋转 180 或 -180 时,我走错了路。
    • 别担心...玩得开心!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多