2013-01-19 64 views
1

我需要一些幫助。我正在製作的遊戲是一款自上而下的2D遊戲。我的角色已經可以移動並射擊子彈了。我面臨的問題是讓子彈射向遊標的方向。獨立子彈的相對移動(HTML5/Javascript)

我已經這樣做了,但問題是,當我拍攝多個子彈時,所有子彈都會改變方向以走向我的光標。我認爲需要做的是每一顆子彈都需要分配它的速度,所以當我拍攝另一顆子彈時它不會改變。子彈是一個對象,所以我不知道我做錯了什麼。

Bullet.prototype.draw = function() { 
    this.drawX += (mouseX - this.drawX) * 0.01 ; 
    this.drawY += (mouseY - this.drawY) * 0.01 ; 
    ctxbullet.drawImage(imgSprite, this.srcX, this.srcY, 
     this.width, this.height, this.drawX, this.drawY, 10, 8); 
}; 

正如你可以看到每一個子彈都遵循這裏的規則和邏輯。

另一個問題是子彈不能以恆定的速度運行。

非常感謝。

+0

如果你正在尋找一種能模仿子彈的彈道軌跡的算法,這應該幫助 - http://gamedev.stackexchange.com/a/19586 – Kyle

回答

0

它看起來像你在該函數中使用的mouseX和mouseY屬性是在別處定義的。這意味着當變量在此函數之外被更新時,用於更新drawX和drawY的數字也將發生變化。

您需要做的是在創建時跟蹤mouseX和mouseY的本地副本。我不知道代碼的其餘部分是什麼樣子,但我會猜測一下。

function Bullet(x, y) { 
    this.srcX = x; 
    this.srcY = y; 
    // keep track of original mouse coordinates 
    this.mouseX = mouseX; 
    this.mouseY = mouseY; 
} 

Bullet.prototype.draw = function() { 
    this.drawX += (this.mouseX - this.drawX) * 0.01; 
    this.drawY += (this.mouseY - this.drawY) * 0.01; 
    ctxbullet.drawImage(
     imgSprite, 
     this.srcX, this.srcY, 
     this.width, this.height, 
     this.drawX, this.drawY, 
     10, 8 
    ); 
}; 

這將確保項目符號在創建時始終朝向鼠標座標行進,但您很快會遇到另一個問題。由於速度是相對於這些鼠標座標的子彈距離(這就是爲什麼你遇到速度不一致的原因),因此子彈將減速停在鼠標座標處。

你需要做的是創建一個矢量從src點到鼠標點以所需的速度。這將允許子彈跟隨那個矢量無窮大(但你知道,實際上是無窮大,希望你一旦超出界限就將它移除)。

function Bullet(x, y) { 
    var dX = mouseX - x, 
     dY = mouseY - y, 
     dist = Math.sqrt(dX * dX + dY * dY) 
    ; 
    // we want our deltas to be proportions of the total distance 
    this.dX = dX/dist; 
    this.dY = dY/dist; 
    this.speed = 5; // arbitrary number 
} 

Bullet.prototype.draw = function() { 
    // I didn't test this, but I think it works 
    this.drawX += this.dX * this.speed; 
    this.drawY += this.dY * this.speed; 
    ctxbullet.drawImage(
     imgSprite, 
     this.srcX, this.srcY, 
     this.width, this.height, 
     this.drawX, this.drawY, 
     10, 8 
    ); 
} 
+0

沒有工作,沒有錯誤顯示,但bulets不show as well – user1993664

+0

即將發生的問題是它表示Dx和Dy未定義 – user1993664

+0

您是否更改了創建子彈時通過x和y座標的代碼?新的子彈(x,y)而不是新的子彈()? – hobberwickey