Jam*_*son 7 javascript canvas collision-detection
我正在使用需要碰撞检测的画布在Javascript中构建游戏,在这种情况下,如果玩家精灵击中一个盒子,则不允许玩家通过该框.
我有一个名为的全局数组blockList,它包含绘制到画布的所有框.它看起来像这样:
var blockList = [[50, 400, 100, 100]];
Run Code Online (Sandbox Code Playgroud)
他们被这样的画布所吸引:
c.fillRect(blockList[0][0], blockList[0][1], blockList[0][2], blockList[0][3]);
Run Code Online (Sandbox Code Playgroud)
我还有一个玩家对象,它有一个更新方法和一个绘制方法.更新根据键盘输入等设置播放器的位置,主游戏循环使用绘制将玩家绘制到画布.玩家被画成这样:
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; }
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,玩家有一定的特性是player.xpos,player.ypos,player.width,player.height.块存在相同的属性.所以我有我需要的一切来实现碰撞检测,我只是不知道该怎么做.我尝试过这样的事情:
if(player.x > blockList[0][0] && player.y > blockList[0][1])
Run Code Online (Sandbox Code Playgroud)
但它远非完美或可玩.
有没有人知道一个简单的方法或函数,能够根据两个对象是否发生冲突返回true或false?
我使用以下函数进行两个矩形之间的碰撞检测:
rect_collision = function(x1, y1, size1, x2, y2, size2) {
var bottom1, bottom2, left1, left2, right1, right2, top1, top2;
left1 = x1 - size1;
right1 = x1 + size1;
top1 = y1 - size1;
bottom1 = y1 + size1;
left2 = x2 - size2;
right2 = x2 + size2;
top2 = y2 - size2;
bottom2 = y2 + size2;
return !(left1 > right2 || left2 > right1 || top1 > bottom2 || top2 > bottom1);
};
Run Code Online (Sandbox Code Playgroud)
这就决定是否两个方形,在中心(x1, y1)和(x2, y2),具有边长2*size1和2*size2分别,是重叠的.它应该很容易改变的定义left1,right1等来对付一般的矩形,而不仅仅是正方形,并使用不同的数据格式.
具体来说,left1是第一个正方形,right1右侧等的左侧.注意,在我的坐标系中,y轴反转(top1< bottom1).