我正在研究2D非旋转矩形碰撞。我可以检测到它,并获得交叉点宽度/高度/位置,但我无法“取消”它。这是我试过的“取消”代码:
if (this.bounds.intersects(player.bounds)) {
var intersection = this.bounds.intersection(player.bounds);
if (player.bounds.bottomRight().x > this.position().x)
player.position().subtract(intersection.width, 0);
else if (player.position().x > this.position().x)
player.position().add(intersection.width, 0);
else if (player.bounds.bottomRight().y > this.position().y)
player.position().subtract(0, intersection.height);
else if (player.position().y > this.position().y)
player.position().add(0, intersection.height);
}
(交叉和交叉方法有效)
玩家是红色方块,墙是黑色方块。 我该如何解决这个问题?
答案 0 :(得分:1)
我不确定你的功能是如何交叉和交叉工作的,但我建议你根据intersection.width < intersection.height
分别更新玩家,比如
if (this.bounds.intersects(player.bounds)) {
var intersection = this.bounds.intersection(player.bounds);
if(intersection.width < intersection.height){
if (player.bounds.bottomRight().x > this.position().x)
player.position().subtract(intersection.width, 0);
else if (player.position().x > this.position().x)
player.position().add(intersection.width, 0);
}else{
if (player.bounds.bottomRight().y > this.position().y)
player.position().subtract(0, intersection.height);
else if (player.position().y > this.position().y)
player.position().add(0, intersection.height);
}
}
根据您检测到碰撞的距离,这可能或多或少都有效。