我的画布上有一辆车,我有一辆汽车轨道作为背景。我想为汽车创造边框。例如,如果汽车接触到不同颜色的像素(如黑色),它应该发出警报。
newImage()是我正在使用的汽车的图像,我想要检测新的颜色
我尝试使用该代码很长一段时间但根本不起作用:
function collideTest(){
var Color = context.getImageData(car - 5, car - 5,60,60);
for (var i = 0; i < 3600; i++) {
if (Color.data[i] == 255) {
alert("Game Over");
}
}
}
这是我的其余代码与汽车图片,以防你需要这些信息:
//Setting the canvas and context
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
//Uploading car
var car = new Image();
car.src = "file:///C:/Users/Saqib/Desktop/Game/img/car-top-view-clipart-red-racing-car-top-view-fe3a%20%281%29.png";
var width = $('#gameCanvas').width();
var height = $('#gameCanvas').height();
//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) {
console.log('a');
if (event.keyCode == 38 || event.keyCode == 40) {
mod = 0;
}
}
//Setting all of the keys
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;
}
}
一点帮助将非常受欢迎。提前致谢。如果您不了解我提供的详细信息,请随时评论您想知道的任何信息,我会在几分钟内给出答复。