我创建了一个敌人对象,所以我可以同时制作多个对象。我有对象的参数采取x,y,x的速度和y的速度。无论我把速度放在哪里,红色方块(敌人)都不会移动。
var c,
ctx,
cWidth,
cHeight,
xCenter,
yCenter,
iBack,
Player,
enemy1,
scale = 40,
speed = scale / 3;
// Controll initialization
var keyState = {};
window.addEventListener('keydown',function(e){
keyState[e.keyCode || e.which] = true;
},true);
window.addEventListener('keyup',function(e){
keyState[e.keyCode || e.which] = false;
},true);
// Initial function to set canvas variables and start loop
function init() {
c = document.getElementById('canvas');
ctx = c.getContext('2d');
cWidth = c.width;
cHeight = c.height;
xCenter = cWidth / 2;
yCenter = cHeight / 2;
iBack = new Image(50, 50);
iBack.src = 'pics/background1.jpg';
Player =
{
playerX: xCenter - (scale / 2),
playerY: yCenter - (scale / 2),
speed: speed,
draw: function() {
ctx.beginPath();
ctx.rect(Player.playerX, Player.playerY, scale, scale);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
},
checkInput: function() {
if (keyState[65]) {
// A key
Player.playerX = Player.playerX - Player.speed;
} else if (keyState[68]) {
// D key
Player.playerX = Player.playerX + Player.speed;
} else if(keyState[87]) {
// W key
Player.playerY = Player.playerY - Player.speed;
} else if(keyState[83]) {
// S key
Player.playerY = Player.playerY + Player.speed;
}
}
};
// Enemy object
function Enemy(x, y, speedX, speedY)
{
this.x = x;
this.y = y;
this.speedX = speedX;
this.speedY = speedY;
this.draw = function () {
ctx.beginPath();
ctx.rect(this.x + this.speedX, this.y + this.speedY, scale, scale);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
};
}
enemy1 = new Enemy(0, (cHeight / 2) - (scale / 2), 10, 10);
setInterval(draw, 60);
}
function draw() {
// Input
Player.checkInput();
// Draw Background
//ctx.drawImage(iBack, 0, 0, cWidth, cHeight);
ctx.beginPath();
ctx.rect(0, 0, cWidth, cHeight);
ctx.fillStyle = 'white';
ctx.fill();
ctx.stroke();
ctx.closePath();
// Draw Player
Player.draw();
// Draw Enemy
enemy1.draw();
// Collision
playerCollision();
}
function playerCollision() {
// Collision with walls
if (Player.playerX <= 0) {
Player.playerX = 0;
} else if (Player.playerX + scale >= cWidth) {
Player.playerX = cWidth - scale;
} else if (Player.playerY <= 0) {
Player.playerY = 0;
} else if (Player.playerY + scale >= cHeight) {
Player.playerY = cHeight - scale;
}
// Collsion with enemys
}
答案 0 :(得分:0)
你没有任何导致敌人x
值改变的东西。你只是用x + speed
绘制它,但这不会让它移动。那将永远只是把它画出来。
通常在setInterval()
中,而不是直接调用draw()
,创建一个名为run()
的函数,在调用draw()
之前应该做一些工作以显示更改那工作。
在run()
中,你应该为每个敌人做点什么,比如enemy.x += enemy.speed
。然后,当你画画时,每一帧都会以速度移动。