IAmTheAg
IAmTheAg

Reputation: 351

How can I discover which side of a rectangle a collision occurred on?

I have been struggling for a while with something that seems basic. I can't think of an effective mathematical way to look at this problem. The language I am using is Objective-C, but I can convert pretty much any language answer because it is essentially just math.

I have two squares, one being the player, on being an obstacle. The player can move, the obstacle can't. The end goal is to tell which side it came from upon collision. For example, when I am moving down it detects that I hit the top of the obstacle.

Here is what I know:

  1. The location of the player both before and after the collision
  2. Whether or not there is any intersection taking place
  3. Almost all other aspects of the movement (velocity, directional movement, etc.)

I will provide as much information as I can, but all I need is a general method for doing this. There seems to be so many ways to approach this, but every one has flaws :/

I am not really asking for code, although that would be nice, I just need a concept to get to working.

Upvotes: 2

Views: 301

Answers (1)

Vikram Bhat
Vikram Bhat

Reputation: 6246

Calculate on which side of the center of the obstacle rectangle is the center of the player rectangle just before the collision. The center is mean of max and min points in rectangle. This can be done using difference of x and y co-ordinates of both center. Remember to take the cordinate which is less than sum of l1/2 + l2/2 . conclusions:-

    (x1,y1) = center of obstacle
    (x2,y2) = center of player
     dx = y1-y2
     dy = x1-x2

    l1 & l2 are length of side aligned in that direction

    dx<0 && abs(dx)>(l1/2+l2/2) = left of obstacle

    dx>0 && abs(dx)>(l1/2+l2/2) = right of obstacle

    dy<0 && abs(dy)>(l1/2+l2/2) = below

    dy>0 && abs(dy)>(l1/2+l2/2) = above

Upvotes: 1

Related Questions