我遇到了一个问题。如果有任何帮助,我将不胜感激。
我正在尝试从玩家位置射击到鼠标点击位置。代码没有给我任何错误,根据我的逻辑,它应该可以工作,但它没有
它创建了项目符号对象,仅此而已。
//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);
});
最佳答案
因为您已经在使用 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);
});
并考虑将所有这些输入移动到一个参数对象中。
另外:永远不要在“if”中定义你的程序,而是取消“if not”!
工作版本:http://jsfiddle.net/LyUmZ/4/
编辑:如果 jsfiddle 不工作,你可能遇到了你的浏览器/noscripts xss guard,使用 xss->unsafe reload(在 firefox noscript 中)它应该工作。
关于javascript - JS - 射击 - 鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17430174/