0
\$\begingroup\$

I am trying to come up with a collision function where all the cases are made.

  1. If the player (Who's hit box is a circle) collides with a platform (hit box is a rectangle) from the right the platform will push the player back.

  2. If the player collides with the platform for the top the player will stand on the platform.

  3. If the platform is to the left of the player the player cant move to the left.

I am not asking how to tell if they are colliding or not but which side of the platform they are collide with where each platform is it's own object.

Can someone help me make this function?

\$\endgroup\$
2

1 Answer 1

0
\$\begingroup\$

Since you seem to be just starting out, I'll give you the simplest approach.

First, define rectangles for all of your game objects (including your player) which will serve as their collision bounds. Once you've done that you will need a method that tests for collision between 2 rectangles (if you used the LibGdx rectangles then you can simply call their overlaps() method). This method would look like so:

public boolean overlaps (Rectangle r) {
    return x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y;
}

Then you would iterate through all of your kinetic objects and test them against each other and all the static objects to see if they are colliding (make sure to make this test efficient because you might have many bodies and it's worthless to test objects not remotely close to each other) and react accordingly.

If you want to know which sides collided, you can use a line intersection test (one of the links below explains that) or you could check the objects' velocities to see which direction they had been moving in, which would tell you which side they touched on.

Having the platforms push the player, you could just give the player some velocity and make them stunned (i.e. the user can't control them) until they have been pushed all the way, but these effects are each very specific and would make this question (and my answer) too broad (i.e. answers too many questions). Ask those more specific questions separately after you have tested out your own ideas using my answer and the links below.

Check out these links for more in-depth explanations and/or more complex approaches:

  1. https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
  2. http://devmag.org.za/2009/04/13/basic-collision-detection-in-2d-part-1/
  3. https://katyscode.wordpress.com/2013/01/18/2d-platform-games-collision-detection-for-dummies/
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .