2013-02-13 46 views
4

我正在制作一款自上而下的射击游戏HTML5。我正在试图让我的角色面对角度射击子弹。HTML5-JS:从子弹射击子弹

我的角色总是面向鼠标位置(旋转)。所以,当我发射子弹时,我需要考虑轮换。

我几乎在那里,唯一的问题是子弹开始我的实际鼠标位置,虽然 - 它在正确的朝向方向移动。

我相信我的数学是从我的速度变量中:

var b = new Rectangle(this.x + (this.width/2) - 4, this.y + (this.height/2) - 4, 8, 8); 

var velocityInstance = new Vector2(0, 0); 
velocityInstance.x = input.mouseX - (this.localX + this.width/2); 
velocityInstance.y = input.mouseY - (this.localY + this.height/2); 

var bulletInstance = new Bullet(velocityInstance, b, this.bullets.length + 1); 

this.bullets.push(bulletInstance); 
this.shotBullet = true; 

“这”指的是我的球员。 localX/Y是我角色的中心位置(他总是在屏幕中央,场景在他身边移动)。

希望如果有人能为我检查这个。谢谢!

------编辑------

这里是我的子弹功能:

Bullet = function(vel, rectangle, index){ 

    this.velocity = vel; 
    this.rect = rectangle; 
    this.index = index; 

    this.Update = function(){ 
     this.rect.x += this.velocity.x; 
     this.rect.y += this.velocity.y; 

     //Collisions 
     for(var c = 0; c < GameObjects.length; c++){ 
      if(this.rect.Intersects(GameObjects[c])){ 
       console.debug("Bullet Hit: " + GameObjects[c].tag); 

       //Player.bullets.splice(index, 1); 
      } 
     } 
    }; 

    this.Draw = function(ctx){ 

     this.rect.Draw(ctxMap); 
    }; 

}; 
+0

如果子弹始终应该来自该字符,为什么在计算中会提及'input.mouseX'或'input.mouseY'?这些值决定子弹的方向,而不是位置。 – jbabey 2013-02-13 15:17:59

+0

如果子弹向正确的方向移动,那不是你的速度 - 这是你的子弹的初始位置。我认为你将它设置为(input.mouseX,input.mouseY)而不是(this.localX + this.width/2,this.localY + this.height/2),但是你没有向我们展示代码的位置。 – 2013-02-13 15:22:24

+0

我更新了我的问题。我最初似乎没问题?我正在使用球员的位置。 – 2013-02-13 15:27:10

回答

3

其实,我会推荐而不是使用trig函数,只是为了提高效率。 Math.atan2,Math.cos和Math.sin可能会变得昂贵。

您已经(略重命名)

var deltaX = input.mouseX - (this.localX + this.width/2); 
var deltaY = input.mouseY - (this.localY + this.height/2); 

为什么就不能跳这种方式?

var magnitude = Math.sqrt(deltaX * deltaX + deltaY * deltaY); 
var velocityScale = bulletSpeed/magnitude; 
velocityInstance.x = deltaX * velocityScale; 
velocityInstance.y = deltaY * velocityScale; 

其功能相同,但只使用一个泰勒级数而不是3,因此应该更有效率。越快越好,对吧?

1

想通了。我需要使用Math.cos和Math.sin:

var targetX = input.mouseX - (this.localX + this.width/2); 
var targetY = input.mouseY - (this.localY + this.height/2); 

this.rotation = Math.atan2(targetY, targetX); 

velocityInstance.x = Math.cos(this.rotation) * bulletSpeed; 
velocityInstance.y = Math.sin(this.rotation) * bulletSpeed; 

谢谢反正社区!帮助我让我的头靠近它!

+0

你输入得比我快。当我看到您的更新弹出时,我只是将其作为答案发布。当然,罪与cos会给你一个正常化的矢量,并且你已经加入了子弹速度。干杯! – 2013-02-13 15:52:40