我遇到了一个问题。我将不胜感激任何帮助。
我正试图从玩家位置射击到鼠标点击位置。代码没有给我任何错误,根据我的逻辑,它应该工作,但它不是
它会创建一个子弹对象,但就是这样。
//Bullets
function bullet(id, color, size, speed, x, y, eX, eY) {
this.id = id;
this.color = color;
this.size = size;
this.x = x;
this.y = y;
this.eX = eX;
this.eY = eY;
this.velocityX;
this.velocityY;
this.speed = speed;
}
var bulletList = [];
function addBullet(color, bsize, bspeed, x, y, eX, eY) {
bulletList[bulletId] = new bullet(bulletId, color, bsize, bspeed, x, y, eX, eY);
bulletId += 1;
}
function updateBullet(bullet, player)
{
var dx = (bullet.eX - player.x);
var dy = (bullet.eY - player.y);
var mag = Math.sqrt(dx * dx + dy * dy);
bullet.velocityX = (dx / mag) * speed;
bullet.velocityY = (dy / mag) * speed;
bullet.x += bullet.velocityX;
bullet.y += bullet.velocityY;
}
// Add event listener for `click` events.
canvas.onmousedown = function(e) {
addBullet("black", 10, 2, playerList[0].x, playerList[0].y, e.x, e.y);
}
//draw bullets (taken from drawFrame function)
$.each(bulletList, function (index, bullet) {
updateBullet(bullet, playerList[0]);
ctx.fillStyle = bullet.color;
ctx.fillRect(bullet.x, bullet.y, bullet.size, bullet.size);
});
答案 0 :(得分:3)
由于您已经在使用jQuery,请更改行
canvas.onmousedown = function(e) {
addBullet("black", 10, 2, playerList[0].x, playerList[0].y, e.x, e.y);
}
到
$(canvas).mousedown(function (e) {
addBullet("black", 10, 2, playerList[0].x, playerList[0].y, e.clientX, e.clientY);
});
并考虑将所有这些输入移动到param对象中。
另外:永远不要在'if'中定义你的程序,而是取消'if not'!
编辑:如果jsfiddle不起作用,你可能已经遇到浏览器/ noscripts xss guard,使用xss-> unsafe reload(在firefox noscript中)它应该可以工作。