私は、衝突検出が必要なキャンバスを使用してJavascriptでゲームを構築しています。この場合、プレーヤースプライトがボックスに当たった場合、プレーヤーはボックスを通過できません。Javascript canvas collision detection
私はblockList
というグローバル配列を持ち、キャンバスに描画されるすべてのボックスを保持しています。それは次のようになります。
var blockList = [[50, 400, 100, 100]];
そして、彼らはこのようなキャンバスに描かれている:私も更新方法とdrawメソッドを持っている選手オブジェクトを、持っている
c.fillRect(blockList[0][0], blockList[0][1], blockList[0][2], blockList[0][3]);
。 Updateは、キーボード入力などに基づいてプレーヤーの位置を設定し、メインのゲームループが描画を使用してプレーヤーをキャンバスに描画します。プレイヤーは次のように描かれている:
this.draw = function(timestamp) {
if(this.state == "idle") {
c.drawImage(this.idleSprite, this.idleSprite.frameWidth * this.idleSprite.frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, this.xpos, this.ypos, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
if(timestamp - this.lastDraw > this.idleSprite.updateInterval) {
this.lastDraw = timestamp;
if(this.idleSprite.frameCount < this.idleSprite.frames - 1) { this.idleSprite.frameCount++; } else { this.idleSprite.frameCount = 0; }
}
} else if(this.state == "running") {
var height = 0;
if(this.facing == "left") { height = 37; }
c.drawImage(this.runningSprite, this.runningSprite.frameWidth * this.runningSprite.frameCount, height, this.runningSprite.frameWidth, this.runningSprite.frameHeight, this.xpos, this.ypos, this.runningSprite.frameWidth, this.runningSprite.frameHeight);
if(timestamp - this.lastDraw > this.runningSprite.updateInterval) {
this.lastDraw = timestamp;
if(this.runningSprite.frameCount < this.runningSprite.frames - 1) { this.runningSprite.frameCount++; } else { this.runningSprite.frameCount = 0; }
}
}
}
さて、プレイヤーがplayer.xpos
、player.ypos
、player.width
、player.height
である特定の性質を有します。ブロックには同じプロパティが存在します。だから、私は衝突の検出を促すために必要なこと全てを持っているので、それをどうやって行うのか分かりません。私は次のようなことをやろうとしました:
if(player.x > blockList[0][0] && player.y > blockList[0][1])
しかし、それは完璧か再生可能ではありません。
誰かが、2つのオブジェクトが衝突しているかどうかに基づいて、trueまたはfalseを返すことができる簡単なメソッドまたは関数を知っていますか?