Quantcast
Channel: Question and Answer » libgdx
Viewing all articles
Browse latest Browse all 434

Basic 2d platform collision detection algorithm has a slight bug (Java)

$
0
0

I’m trying to implement collision detection between Player (the main character) and a Platform. They are both modelled as rectangles; when player hits the side of a platform he should bounce off it and when player hits the top of a platform he should glide (move) along it. The problem I’m facing is that sometimes the player bounces when he lands on top of the platform (near an edge) rather than glide along it.

For the collision detection, I’m using the Intersector class (LibGDX). If you are unfamiliar with this class, all it does is create the new rectangle that occurs when two rectangles intersect (i.e. the rectangle shaded green below).

enter image description here

Code:

for (int i = 0; i < list.size(); i++) {
            //An object from a list of objects that the player can collide with
            GameObject go1 = list.get(i);
            //True if the object is of type platform
            boolean playerPlatformCollision = (go1.getType() == ObjectType.PLATFORM);
            //If the two objects being compared are Player and Platform
            if (playerPlatformCollision) {
                Rectangle objectRect = go1.getRect();
                //If the Player and Platform overlap
                if (player.getRect().overlaps(objectRect)) {
                    //The resulting rectangle from the overlap (as shaded green in the above pic)
                    Rectangle intersection = new Rectangle();
                    Intersector.intersectRectangles(player.getRect(),
                            objectRect, intersection);

                    //If the Player collides with bottom side of platform
                    if (intersection.y > player.getRect().y) {
                        player.setySpeed(-getySpeed()); // Make him bounce downwards 
                    }

                    // If the Player collides with left side of platform
                    if (intersection.x > player.getRect().x) {
                         player.bounce(); // Make him bounce
                    }

                    // If the player collides with the top side of platform
                    if (intersection.y + intersection.height < player.getRect().y
                            + player.getRect().height) {
                        player.setGravity(false);
                        player.onPlatform(true);
                    } else {
                        player.onPlatform(false);
                    }
                }
            }

Is there any sort of trick I can use for this? Haven’t been able to find anything online that works.


Viewing all articles
Browse latest Browse all 434

Trending Articles