javascript - HTML5 canvas 游戏将子弹射向鼠标点。

标签 javascript jquery html canvas

现在。我已将其设置为从 Angular 色的方向射击子弹。但我希望能够将子弹射到鼠标点,让玩家更轻松。

现在是

if(gun_1[i].direction == 2){ gun_1[i].x -= gun_1[i].speed * modifier};
if(gun_1[i].direction == 3){ gun_1[i].x += gun_1[i].speed * modifier};
if(gun_1[i].direction == 1){ gun_1[i].y -= gun_1[i].speed * modifier};
if(gun_1[i].direction == 4){ gun_1[i].y += gun_1[i].speed * modifier };
if(gun_1[i].direction == 5){ gun_1[i].y -= gun_1[i].speed * modifier; gun_1[i].x -= gun_1[i].speed * modifier };
if(gun_1[i].direction == 7){ gun_1[i].y += gun_1[i].speed * modifier; gun_1[i].x -= gun_1[i].speed * modifier };
if(gun_1[i].direction == 6){ gun_1[i].y -= gun_1[i].speed * modifier; gun_1[i].x += gun_1[i].speed * modifier };
if(gun_1[i].direction == 8){ gun_1[i].y += gun_1[i].speed * modifier; gun_1[i].x += gun_1[i].speed * modifier };

我希望能够拍摄到鼠标点击的位置。如果可能。

最佳答案

当然,这并不难。但是您也可以做很多事情来改进当前的设计。首先,添加 velocityXvelocityY 字段,这样在每一步你只需要更新子弹的位置:

gun_1[i].x += gun_1[i].velocityX
gun_1[i].y += gun_1[i].velocityY

然后当按下鼠标时,设置子弹的速度:

canvas.onmousedown = function(e) {
   var dx = (e.x - character.x);
   var dy = (e.y - character.y);
   var mag = Math.sqrt(dx * dx + dy * dy);

   // whatever you need to do to get gun_1[i]

   gun_1[i].velocityX = (dx / mag) * speed;
   gun_1[i].velocityY = (dy / mag) * speed;
}

如果您对向量有所了解,我们只是将方向向量归一化并乘以标量初始速度。

关于javascript - HTML5 canvas 游戏将子弹射向鼠标点。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16756479/

相关文章:

jQuery 验证多个不相等的输入

Javascript/jQuery 防止双重事件触发

javascript - Play 事件将在 videojs 中无限循环

javascript - 如何在 JavaScript 中创建高级倒数计时器?

javascript - 在这个特定的示例中,作者为什么在 for...in 循环模式中使用 if...hasOwnProperty?

javascript - Timesheet.js 未启动

php - HTML 呈现问题 - 适用于 Mozilla Firefox,但不适用于 Google Chrome

html - 边框在不同的行中显得更粗

javascript - JavaScript 中的实时电子邮件验证

javascript - 如何从开始和结束开始匹配,并在javascript中替换字符串