我正在尝试使用HTML5画布和JavaScript开发游戏,但是我在没有使用两个对象的(x,y)坐标进行硬编码的情况下检测碰撞时遇到了问题。根据我的研究,我找到了一个常见的算法来检查两个对象是否发生了碰撞,即
Object1 = a moving player
Object2 = fixed (x,y) points. Non movable object
(object1.x < object2.x + object2.width && object1.x + object1.width > object2.x &&
object1.y < object2.y + object2.height && object1.y + object1.height > object2.y)
我尝试了它并与其他代码一起开发,它可以检测到碰撞。但是我在处理碰撞方面遇到了一个问题,在左侧
的情况下可以正常工作,但当object1
移动到object2
的顶部,底部或右侧
时,它会返回到object2
的左侧
。换句话说,如果object1
向上/向下或向右移动,则会返回到左侧。非常感谢任何形式的帮助。
function collide(object1, object2){
//object1 player
this.x = object1.x;
this.y = object1.y;
this.w = object1.w;
this.h = object1.h;
//object2 any object
this.x2 = object2.x;
this.y2 = object2.y;
this.w2 = object2.w;
this.h2 = object2.h;
//collisions
var isCorrect = false;
var side = 0;
if ((this.x < this.x2 + this.w2) && (this.x + this.w > this.x2)
&& (this.y < this.y2 + this.h2) && (this.h + this.y > this.y2)){
isCorrect = true;
}
if (this.x + this.w > this.x2){
//left check
side = 1;
}else if (this.x < this.x2 + this.w2){
//right check
side = 2;
}else if (this.y + this.h > this.y2){
//bottom check
side = 3;
}else if (this.y < this.y2 + this.h2){
//top check
side = 4;
}
if (isCorrect){
if ((this.x + this.w > this.x2) && side == 1){
playerObj.x -= 5;
}else if ((this.x < this.x2 + this.w2) && side == 2){
playerObj.x += 5;
}else if ((this.y + this.h > this.y2) && side == 3){
playerObj.y += 5;
}else if ((this.y < this.y2 + this.h2) && side == 4){
playerObj.y -= 5;
}
}
}