0
votes

I need to block two rectangles colliding with each other in Action Script. The code I have works only dimentionally(only a X on X collision or a Y on Y). When I test if it's colliding on the X axis and the Y, they interfere.

function collisionTest(obj1, obj2) {

var b1 = getBound(obj1);
var b2 = getBound(obj2);

if(((b1.x < b2.x + b2.width) && (b1.x + b1.width > b2.x)) && ((b1.y + b1.height > b2.y) && (b1.y < b2.y + b2.height)))
{
    if(b1.x + b1.width > b2.x + b2.width)
        obj1.x = b2.x + b2.width;
    else if(b1.x < b2.x)
        obj1.x = b2.x - obj1.width;
    else if(b1.y < b2.y)
        obj1.y = b2.y - obj1.height;
    else if(b1.y + b1.height > b2.y + b2.height)
        obj1.y = b2.y + b2.height;
}

}

If there is any other way to test for a collision and block it, then please tell me, but I've searched on Google, and stackoverflow, and haven't found anything useful for blocking the collision, however I've found a lot about testing for them.

3

3 Answers

0
votes

Step 1: Get Box2d. Step 2: Thank me :)

In all seriousness, use well known, highly optimized libraries. You probably have more mechanics to go with collision.

If collision is the only thing you want, then I would suggest you use hitTest. The advantage to that is that you can compare irregular shapes with each other, not just boxes. You simply test each time your objects move, if hitTest is true. If it is, then you revert to the previous state, or put them one next to another.

Another variation of this method is to add an "aura" to your moving object. If the aura hitTests the target object, STOP. This way you don't have to perform an extra step to reposition the object.

Hope I expressed myself clearly, I am half asleep :D

0
votes

hitTestObject works just fine for two rectangular objects :

if (obj1.hitTestObject(obj2))
{
    // handle collision
}
0
votes

If it is pure rectangle collisions, you can use the intersecting rectangle method.

var overlapRect:Rectangle = RECTANGLE1.intersection(RECTANGLE2);

This will dump the info of a collision like this one into a overlapRect.

enter image description here

From there you can use logic to find out where the collision is happening and move one of the rectangle away from the other using the intersection width and height.

enter image description here