HTML5帆布游戏射击子弹到鼠标点.

Bri*_*ian 2 javascript jquery html5 canvas

马上.我有它设置从我的角色方向射击子弹.但我希望能够向鼠标点射子弹,让玩家更轻松.

现在是的

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 };
Run Code Online (Sandbox Code Playgroud)

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

Zon*_*ong 5

当然,这不是太难.但是,您可以做很多事情来改善您当前的设计.首先,添加velocityXvelocityY字段,以便在每个步骤中只需更新项目符号的位置:

gun_1[i].x += gun_1[i].velocityX
gun_1[i].y += gun_1[i].velocityY
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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