2014-02-23 59 views
0

如果一个矩形与另一个矩形发生碰撞并且碰撞与每个对象相关(左,右,上,下),我遇到了麻烦。矩形碰撞测试问题

我的代码在理论上工作良好,但存在逻辑问题,当对象进入另一个对象的左侧时存在误报。我设置的参数意味着顶部碰撞和左侧碰撞都变为真实,而实际上只有左侧真实。

image of problem

如何才能停止在我的代码双重利好发生,我只需要基本的矩形碰撞,仅此而已。谢谢。

//Col on top? 
if (Obj1.getRect(this).bottom - vSpeed < Obj2.getRect(this).bottom && 
    Obj1.getRect(this).bottom - vSpeed > Obj2.getRect(this).top) 
{   
    if (Obj1.getRect(this).right + hSpeed > Obj2.getRect(this).left && 
     Obj1.getRect(this).left + hSpeed < Obj2.getRect(this).right) 
    { 

     Obj1.y = Obj2.y - Obj1.height; 
     vSpeed = 0; 

     colTop = true; 

    } 
} 
    //Col on Bottom? 
else if (Obj1.getRect(this).top - vSpeed > Obj2.getRect(this).top && 
     Obj1.getRect(this).top - vSpeed < Obj2.getRect(this).bottom) 
{  
    if (Obj1.getRect(this).right + hSpeed > Obj2.getRect(this).left && 
     Obj1.getRect(this).left + hSpeed < Obj2.getRect(this).right) 
    { 

     Obj1.y = Obj2.y + Obj2.height; 
     vSpeed = 0; 

     colBot = true; 

    }   
} 

//Col on left side? 
if (Obj1.getRect(this).right + hSpeed > Obj2.getRect(this).left && 
    Obj1.getRect(this).right + hSpeed < Obj2.getRect(this).right) 
{  
    if (Obj1.getRect(this).bottom - vSpeed > Obj2.getRect(this).top && 
     Obj1.getRect(this).top - vSpeed < Obj2.getRect(this).bottom) 
    { 

     Obj1.x = Obj2.x - (Obj2.width * 0.5); 
     hSpeed = 0; 

     colLeft = true; 

    } 
} 
    //Col on right side? 
else if (Obj1.getRect(this).left + hSpeed > Obj2.getRect(this).left && 
     Obj1.getRect(this).left + hSpeed < Obj2.getRect(this).right) 
{  
    if (Obj1.getRect(this).bottom - vSpeed > Obj2.getRect(this).top && 
     Obj1.getRect(this).top - vSpeed < Obj2.getRect(this).bottom) 
    { 

     Obj1.x = (Obj2.x + Obj2.width) + (Obj1.width * 0.5); 
     hSpeed = 0; 

     colRight = true; 

    } 
} 
+0

不知道你的意思,你的意思是我应该删除最后的改动OBJ1的共同ORDS和速度改变了我的if语句吗? 这会导致同样的问题,当玩家移动到Obj2的左侧并将Obj1移动到顶部时,它会看到Top为true。如果我明白了你的意思。 – user3307694

回答

0

您需要通过解析对象的相对速度来区分顶部碰撞和左碰撞。你不能使用坐标来解析顶部/左边的碰撞,因为如果一个矩形的左上角点在另一个矩形内,它们都是真的。因此,请将您的Obj1和速度更改代码从您的if语句数组中移出,并按原样保留其余代码。然后你检查这样的速度:

if (colTop) 
    if (Obj1.getRect(this).bottom > Obj2.getRect(this).top) 
     colTop=false; 

等,其他碰撞变量。这个代码的意思是:“如果Obj1已经的底部在Obj2的顶端,那么在这个框架中我们没有达到顶端”。所以,只剩下左侧碰撞标志。只有这样你才能检查结果碰撞变量并调整坐标和速度

0

椋鸟库提供了很好的碰撞检测,包括简单的矩形碰撞。你的方法在每一帧都被调用吗? 所有你需要为​​ 是:

var bounds1:Rectangle = image1.bounds; 
var bounds2:Rectangle = image2.bounds; 

if (bounds1.intersects(bounds2)) 
    trace("Collision!"); 

collision detection