我正在制作一个游戏,你的鼠标是一个十字准线,你点击僵尸在屏幕上移动。我有麻烦弄清楚如何找到鼠标是否点击了僵尸。僵尸是用JavaScript制作的,所以我不能在HTML中使用onclick属性。这是我的代码。
var mouseX;
var mouseY;
$(document).ready(function(){
var canvasWidth = 640;
var canvasHeight = 480;
var canvas = $("#gameCanvas")[0];
var context = canvas.getContext("2d");
var score = 0;
var timer = 0;
var spawnZombie = false;
//crosshair
var crossHair = new Image();
var crosshairX = 50;
var crosshairY = 50;
crossHair.src = "media/crosshair.png";
//zombies
var zombies = [];
var zombieLeft = new Image();
zombieLeft.src = "media/zombieLEFT.gif";
var zombieRight = new Image();
zombieRight.src = "media/zombieRIGHT.gif";
var fps = 30;
setInterval(function(){
update();
draw();
}, 1000/fps);
function update(){
timer += 1;
crosshairX = mouseX - 445;
crosshairY = mouseY - 125;
if(timer >= 70){
timer = 0;
spawnZombie = true;
}
zombies.forEach(function(zombie) {
zombie.update();
document.body.onmousedown = function() {
console.log(zombie.x.toString() + ", " + zombie.y.toString());
//if(mouseX)
};
});
zombies = zombies.filter(function(zombie){
return zombie.active;
});
if(spawnZombie){
zombies.push(Zombie(null, "left"));
zombies.push(Zombie(null, "right"));
spawnZombie = false;
}
}
function draw(){
context.clearRect(0,0, canvasWidth, canvasHeight);
context.fillStyle = "#000";
context.font = "20px Comic Sans MS";
context.fillText("Score: " + score, 50, 50);
zombies.forEach(function(zombie) {
zombie.draw();
});
context.drawImage(crossHair, crosshairX, crosshairY, 100, 100);
}
function Zombie(I, dir){
I = I || {};
I.active = true;
I.speed = 5;
I.y = getRandomInt(50, 350);
if(dir == "left"){
I.x = 800;
}
else if(dir == "right"){
I.x = -100;
}
I.width = 100;
I.height = 100;
I.inBounds = function() {
return I.x >= 0 && I.x <= canvasWidth &&
I.y >= 0 && I.y <= canvasHeight;
};
I.draw = function(){
if(dir == "left"){
context.drawImage(zombieLeft, this.x, this.y, this.width, this.height);
}
else if(dir == "right"){
context.drawImage(zombieRight, this.x, this.y, this.width, this.height);
}
};
I.update = function(){
if(dir == "left"){
this.x -= this.speed;
}
else if(dir == "right"){
this.x += this.speed;
}
};
I.onclick = function(){
I.remove();
};
return I;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
});
$( document ).on( "mousemove", function( event ) {
mouseX = event.pageX;
mouseY = event.pageY;
});
这是我试图检测僵尸是否已在我的更新功能中点击的具体位置
zombies.forEach(function(zombie) {
zombie.update();
document.body.onmousedown = function() {
console.log(zombie.x.toString() + ", " + zombie.y.toString());
//if(mouseX)
};
});
答案 0 :(得分:0)
我无法在HTML中使用
onclick
属性。
但可以在您的javascript中使用addEventListener
方法:
<强>例如强>
zombieLeft.addEventListener('click', myFunction, false);
答案 1 :(得分:0)
document.body.onmousedown = function(event) {
console.log(zombie.x.toString() + ", " + zombie.y.toString());
if(event.pageX == zombie.x && event.pageY == zombie.y){
//Zombie clicked
}
};
这是伪代码。您可以附加事件,您可以检查x和y。