我正在用 HTML5 Canvas 制作游戏。我试图让子弹相对于玩家 velX 和 velY(vx 和 vy)射击,这是代码,问题是它的速度应该是恒定的。
这是问题出现的部分:
if (keys[32]) {
bullet.push({
x: player.x,
y: player.y,
vx: player.vx * 10,
vy: player.vy * 10,
})
}
这是游戏的主要代码:
<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,
s: 5,
vx: 0,
vy: 0,
}
var enemy = {
x: 0,
y: 0,
s: 4,
vx: 0,
vy: 0,
}
var bullet = []
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.s) {
player.vy++;
}
}
if (keys[38]) {
if (player.vy > -player.s) {
player.vy--;
}
}
if (keys[39]) {
if (player.vx < player.s) {
player.vx++;
}
}
if (keys[37]) {
if (player.vx > -player.s) {
player.vx--;
}
}
if (keys[32]) {
bullet.push({
x: player.x,
y: player.y,
vx: player.vx * 10,
vy: player.vy * 10,
})
}
for (i = 0; i < bullet.length; i++) {
bullet[i].x += bullet[i].vx
bullet[i].y += bullet[i].vy
ctx.beginPath()
ctx.arc(bullet[i].x, bullet[i].y, 3, 0, Math.PI * 2, false)
ctx.fillStyle = "red"
ctx.fill()
ctx.closePath()
}
player.vx *= friction;
player.vy *= friction;
player.x += player.vx;
player.y += player.vy;
var dx = (enemy.x - player.x);
var dy = (enemy.y - player.y);
var mag = Math.sqrt(dx * dx + dy * dy);
enemy.vx = (dx / mag) * -enemy.s,
enemy.vy = (dy / mag) * -enemy.s,
enemy.x += enemy.vx
enemy.y += enemy.vy
ctx.beginPath()
ctx.arc(player.x, player.y, 8, 0, Math.PI * 2, false)
ctx.fillStyle = "black"
ctx.fill()
ctx.closePath()
ctx.beginPath()
ctx.arc(enemy.x, enemy.y, 8, 0, Math.PI * 2, false)
ctx.fillStyle = "red"
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>