我用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>
玩家只是在屏幕上上下移动,但我希望它朝着它面向的方向移动。
答案 0 :(得分: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()是trig函数,以弧度为角度作为参数。因此,转换因子为Math.PI / 180。
希望这可以解决问题。我在平板电脑上,无法从这里轻松测试......