如何让玩家的控件变得像,左右只是改变方向然后向前移动,在当前方向向下移动,而不是我目前在我的代码中控制:
<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>
答案 0 :(得分:1)
这样的事情会起作用吗?
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;
}
}