所以基本上我有一些汽车的代码有速度和一切,现在我想要另一个具有相同属性的汽车。所以我复制了整个代码并更改了其他汽车网址和所有变量。我的画布上有2辆车但是它们一直闪烁着。我不知道为什么会这样。
你可以在JsBin上看到它:
http://jsbin.com/fekutakime/3/edit
我复制的汽车代码是:
//Setting the canvas and context
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
//Uploading car
var car = new Image();
car.src = "http://images.clipartpanda.com/car-top-view-clipart-red-racing-car-top-view-fe3a.png";
//Setting properties of car
var x = 450;
var y = 730;
var speed = 10;
var angle = 990;
var mod = 0;
//Event listeners for keys
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keyup_handler, false);
//Interval for animation
var moveInterval = setInterval(function () {
draw();
}, 30);
//Drawing the car turning and changing speed
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();
}
//Setting the keys
function keyup_handler(event) {
if (event.keyCode == 38 || event.keyCode == 40) {
mod = 0;
}
}
//Setting all of the keys
function keypress_handler(event) {
console.log(x, y);
if (event.keyCode == 38) {
mod = 1;
}
if (event.keyCode == 40) {
mod = -1;
}
if (event.keyCode == 37) {
angle -= 5;
}
if (event.keyCode == 39) {
angle += 5;
}
}