2015-11-05 82 views
1

在用戶可以用槍射擊子彈的簡單畫布應用上工作。 (點擊=新的項目符號,箭頭鍵=新的方向)JavaScript畫布:帶有碰撞檢測的「隨機」錯誤

工作幾乎完美,除了看似「隨機」出現的地方,如果方向改變,碰撞將失敗。我的jsFiddle。有關片段:

Bullet.prototype - 動畫():

animate: function() { 
    if (gun.velocity.direction === keys.left) { 
     this.coordinates.x -= this.velocity.speed.x; 
    } else if (gun.velocity.direction === keys.up) { 
     this.coordinates.y += this.velocity.speed.y; 
    } else if (gun.velocity.direction === keys.right) { 
     this.coordinates.x += this.velocity.speed.x; 
    } else if (gun.velocity.direction === keys.down) { 
     this.coordinates.y -= this.velocity.speed.y; 
    } 
    return this; 
}, 

Bullet.prototype - 碰撞():

collision: function (str) { 
    if (str === 'boundary') { 
     if (this.coordinates.x + this.velocity.speed.x > canvas.width || this.coordinates.x + this.velocity.speed.x < 0) { 
       this.velocity.speed.x = -this.velocity.speed.x; 
      } else if (this.coordinates.y + this.velocity.speed.y > canvas.height || this.coordinates.y + this.velocity.speed.y < 0) { 
       this.velocity.speed.y = -this.velocity.speed.y; 
      } 
     } 
    } 

主要處理:

document.onkeydown = function (e) { 
    e = e.keyCode; 
    if (e === keys.left) { 
     gun.velocity.direction = keys.left; 
    } else if (e === keys.up) { 
     gun.velocity.direction = keys.up; 
    } else if (e === keys.right) { 
     gun.velocity.direction = keys.right; 
    } else if (e === keys.down) { 
     gun.velocity.direction = keys.down; 
    } 
}; 

我如何弄清楚爲什麼會發生這種情況,我該如何阻止它?

回答

1

好吧,我看了看,發現你的錯誤。

你有子彈,你已經給出屬性速度是兩個值x,你也有一個方向。當爲子彈設置動畫時,您需要檢查方向,並根據方向僅向x或y添加正確方向的子彈。但是當你測試子彈是否撞到牆壁時,你會忽略方向並測試子彈的速度。整個時間你的子彈x和y的速度都不等於零。你碰撞測試是測試對角線移動的子彈。

如果添加的這段代碼

ctx.strokeStyle = this.color; 
    ctx.beginPath(); 
    // draw a line in the direction you are testing the wall to be 
    ctx.moveTo(this.coordinates.x, this.coordinates.y); 
    ctx.lineTo(this.coordinates.x + this.velocity.speed.x*10, this.coordinates.y + this.velocity.speed.y*10); 
    ctx.stroke(); 

,你渲染子彈,你會看到,子彈沒有在受this.velocity.speed指示的方向行駛,而是你使用這些值來測試牆。

有一個簡單的修復需要改變很多。

該怎麼做。

對於每個子彈 保持速度作爲一個單一的數字。 創建delta.xdelta.y作爲項目符號向量。 保持方向爲單個值。正如你已經擁有。

當你拍攝時使用方向來設置子彈矢量(增量); 上集delta {x:0,y:-1}, 下集delta {x:0,y:1}, 左集delta {x:-1,y:0}, 右集delta {x :1,y:0},

要移動子彈只需添加deltas乘以速度;

bullet.pos.x += bullet.delta.x * bullet.speed; 
bullet.pos.y += bullet.delta.y * bullet.speed; 

速度與方向無關。這是描述隨着時間的推移距離的正值。

Delta x和y確實是子彈方向所需要的全部,但是在將方向保持爲單個值以及兩者匹配時沒有任何傷害。

爲了測試壁

// check if the bullet is moving in the x direction 
// then check if it's about to hit the wall 
if(bullet.delta.x !== 0 && (bullet.pos.x + bullet.delta.x * bullet.speed > wallLoc || 
    bullet.pos.x + bullet.delta.x * bullet.speed < 0)){ 
    bullet.delta.x = -bullet.delta.x; // reverse bullet 
} 

做用於y方向上的相同。

我不知道您是否打算在按下某個鍵時更改所有子彈的方向。如果只是通過所有項目符號並在按下某個鍵時更改那裏的增量。

希望這是明確的。請問是否需要更多信息。