我为我的汽车添加了一些if语句,但没有超出画布的界限,但它仍然过去,所以你能为我调试一下还是只告诉我有什么问题?提前谢谢。
JS: 代码无法正常工作
function update() {
window.requestAnimationFrame(update);
x += speed;
y += speed;
if (x >= $('#gameCanvas').width() - x/2) {
speed = 0;
} else if (x <= x/2) {
speed = 0;
}
x += speed;
if (y >= $('#gameCanvas').height() - y/2) {
speed = 0;
} else if (y <= y/2) {
speed = 0;
}
y += speed;
render();
}
Total js code:
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
var car = new Image();
car.src = "http://thumbs.dreamstime.com/x/compact-yellow-car-top-view-10334412.jpg";
var x = 220;
var y = 200;
var speed = 5;
var angle = 0;
var mod = 0;
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keyup_handler, false);
var moveInterval = setInterval(function () {
draw();
}, 30);
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
x += (speed * mod) * Math.cos(Math.PI / 180 * angle);
y += (speed * mod) * Math.sin(Math.PI / 180 * angle);
context.save();
context.translate(x, y);
context.rotate(Math.PI / 180 * angle);
context.drawImage(car, -(car.width / 2), -(car.height / 2));
context.restore();
}
function update() {
window.requestAnimationFrame(update);
x += speed;
y += speed;
if (x >= $('#gameCanvas').width() - x/2) {
speed = 0;
} else if (x <= x/2) {
speed = 0;
}
x += speed;
if (y >= $('#gameCanvas').height() - y/2) {
speed = 0;
} else if (y <= y/2) {
speed = 0;
}
y += speed;
render();
}
function keyup_handler(event) {
console.log('a');
if (event.keyCode == 38 || event.keyCode == 40) {
mod = 0;
}
}
function keypress_handler(event) {
console.log(event.keyCode);
if (event.keyCode == 38) {
mod = 1;
}
if (event.keyCode == 40) {
mod = -1;
}
if (event.keyCode == 37) {
angle -= 5;
}
if (event.keyCode == 39) {
angle += 5;
}
}