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