1

我怎样才能使播放器的控件像左和右只是改变方向并且向上前进,以及向下回到当前方向,而不是我目前在我的代码中拥有的控件:

<style>
.canvas {
border: 0px;
background-color: #FFF;
width: 1000px;
height: 500px;
position: fixed;
left: 0;
top: 0;
}
</style>

<center>    
<canvas id="canvas" class="canvas" width="1000" height="500"></canvas>
</center>

<script language="javascript">
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")


canvas.width = canvas.style.width = window.innerWidth
canvas.height = canvas.style.height = window.innerHeight
var w = canvas.width
var h = canvas.height

var player = {
x: w / 2,
y: h / 2,
speed: 5,
radius: 8,
vx: 0,
vy: 0,
}

var keys = []
var friction = 0.9

setInterval(draw, 1000/60)
function draw() {
canvas.width = canvas.style.width = window.innerWidth
canvas.height = canvas.style.height = window.innerHeight
w = canvas.width
h = canvas.height

ctx.clearRect(0, 0, w, h)

if (keys[40]) {
    if (player.vy < player.speed) {
        player.vy++;
    }
}
if (keys[38]) {
    if (player.vy > -player.speed) {
        player.vy--;
    }
}
if (keys[39]) {
    if (player.vx < player.speed) {
        player.vx++;
    }
}
if (keys[37]) {
    if (player.vx > -player.speed) {
        player.vx--;
    }
}

player.vx *= friction;
player.vy *= friction;
player.x += player.vx;
player.y += player.vy;

ctx.beginPath()
ctx.arc(player.x, player.y, player.radius, 0, Math.PI * 2, false)
ctx.fillStyle = "black"
ctx.fill()
ctx.closePath()
}

document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
</script>
4

1 回答 1

0

像这样的东西会起作用吗?

player.angle = 0; //Changes depending on the radians the ship is in - currently faces right, defined outside of this.

然后在你得到钥匙的地方使用它:

if (keys[40]) {
    player.vy += Math.sin(player.angle); //Reversed because y goes down as the screen goes up
    player.vx -= Math.cos(player.angle);
}
if (keys[38]) {
    player.vy -= Math.sin(player.angle); //Reversed because y goes up as the screen goes down
    player.vx += Math.cos(player.angle);
}
if (keys[39]) {
    player.angle -= Math.PI / 128;
    if(player.angle < 0) {
        player.angle += Math.PI * 2;
    }
}
if (keys[37]) {
    player.angle += Math.PI / 128;
    if(player.angle >= Math.PI * 2) {
        player.angle -= Math.PI * 2;
    }
}
于 2013-06-11T20:00:40.937 回答