我正在用Javascript创建一个游戏,使用需要碰撞检测的画布,在这种情况下,如果玩家精灵碰到一个盒子,玩家不能通过盒子。Javascript画布碰撞检测
我有一个名为blockList
的全局数组,其中包含所有正在绘制到画布的框。它看起来像这样:
var blockList = [[50, 400, 100, 100]];
而且他们被吸引到画布像这样:
c.fillRect(blockList[0][0], blockList[0][1], blockList[0][2], blockList[0][3]);
我也有一个玩家对象,它有一个更新的方法和draw方法。更新根据键盘输入等设置播放器的位置,draw由主游戏循环用于将播放器绘制到画布上。玩家正在制订这样的:现在
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])
但它远非完美或可播放。
有谁知道一个简单的方法或函数能够返回true或false的基础上,如果两个对象相撞?