Checking what side a rectangle is colliding with another rectangle

My code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
bool left = false;
            bool right = false;
            bool top = false;
            bool bottom = false;

            //check x axis
            if (actor.velocity.X != 0)
            {
                shape.Position = new Vector2f(actor.sprite.Position.X, actor.lastPosition.Y);

                if (shape.GetGlobalBounds().Intersects(obj.sprite.GetGlobalBounds()))
                {
                    if (actor.velocity.X > 0)
                        right = true;
                    else
                        left = true;
                }
            }

            //check y axis
            if (actor.velocity.Y != 0)
            {
                shape.Position = new Vector2f(actor.lastPosition.X, actor.sprite.Position.Y);

                if (shape.GetGlobalBounds().Intersects(obj.sprite.GetGlobalBounds()))
                {
                    if (actor.velocity.Y > 0)
                        bottom = true;
                    else
                        top = true;
                }
            }


It's in c# but it's obviously readable for a C++ programmer. I'm trying to find out what side a rectangle is colliding with. Intersects checks if they're colliding. I don't have time to rest it at the moment so I wanted a second opinion. Thanks!

"shape" is a temp object I'm using to test the new positions with seeing I don't want to modify the actual actor until after collision checks.
Last edited on
There are several considerations.

The best consideration is probably what you have: the 'velocity' is a good indicator of which side properly collided. Other than that, any overlap of the rects at all is fine.

It looks like you are using SFML, but IDK exactly what your objects look like, so the following is kind of a guess -- enough that you can get the idea.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
enum CollidedSide { none, left, top, right, bottom };

CollidedSide which_collision( Actor actor, Object object ) {

    // get an actor with the desired position
    Actor temp = actor;
    temp.update();  // move actor to next position
    FloatRect bounds = temp.shape.GetGlobalBounds();

    // no collision?
    if (!bounds.Intersects(object.sprite.GetGlobalBounds())) {
        return none;
    }

    // which side did it happen on?
    if (System.Math.Abs(actor.velocity.X) < System.Math.Abs(actor.velocity.Y)) {
        if (actor.velocity.Y > 0) return bottom;
        return top;
    } else {
        if (actor.velocity.X > 0) return right;
        return bottom;
    }
}

This assumes that the object that the actor collided with is stationary...

Hope this helps.
Topic archived. No new replies allowed.