Question

I am trying to detect a collision between 2 rectangles and so I am using a rectangle intersection method to determine where the collision is happening.

enter image description here

if (weakRect.y < strongRect.y)
    {

        weakRect.y -= overlapRect.height; << Does nothing
        vSpeed = 0; << Changes int value

    }

This line of code doesn't seem to do anything at all when I run through it, I've tried removing it and adding other stuff but it does not seem to work although other things inside the if statement work.

function rectBlock(strongRect1:MovieClip, weakRect1:MovieClip){

var strongRect:Rectangle = new Rectangle;
var weakRect:Rectangle = new Rectangle;

strongRect = strongRect1.getBounds(stage);
weakRect = weakRect1.getBounds(stage);

var overlapRect:Rectangle = strongRect.intersection(weakRect);

trace (overlapRect)

if (overlapRect.width > overlapRect.height)
{
    if (weakRect.y < strongRect.y)
    {

        weakRect.y -= overlapRect.height;
        vSpeed = 0;

    }
    else if (weakRect.y > strongRect.y)
    {

        weakRect.y += overlapRect.height;
        vSpeed = 0;

    }
}

if (overlapRect.width < overlapRect.height)
{
    if (weakRect.x < strongRect.x)
    {

        weakRect.x -= overlapRect.width;
        hSpeed = 0;

    }
    else if (weakRect.x < strongRect.x)
    {

        weakRect.x += overlapRect.width;
        hSpeed = 0;

    }
}

Even when tracing a "yes" under the if statements it prints it when I am in a collision it just does not move weakRect back out of the collision.

Was it helpful?

Solution

You need to change position of weakRect1(movieclip) not weakRect(rectangle)

weakRect1.y -= overlapRect.height; //<=>weakRect.y -= overlapRect.height;
...
weakRect1.y += overlapRect.height; //<=>weakRect.y += overlapRect.height;
...
weakRect1.x -= overlapRect.width; //<=>weakRect.x -= overlapRect.width;
...
weakRect1.x += overlapRect.width; //<=>weakRect.x += overlapRect.width;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top