Search code examples
libgdxcollision-detection

Moving platform collision detection


I have a moving platform at constant speed and I need to update my player position when my olayer jump ont that platform. But I have problems with collision detection. Here how I try to detect collision between my player's bottom Rectangle and platform Rectangle.

    for(GameObject t2 : list){
                    if(t2 instanceof Platform){

                        platform = (Platform) t2;
                        render.rect(platform.getHitBox().getX(), 
                                    platform.getHitBox().getY(),
                                    platform.getHitBox().getWidth(),
                                    platform.getHitBox().getHeight());

                        platform.update(Gdx.graphics.getDeltaTime(), 0,
                                        player1.getHitBox().getX(), 
                                        Gdx.graphics.getWidth());

                        if(platform.getHitBox().overlaps(player1.getHitBox())
                           ||player1.getHitBox().overlaps(platform.getHitBox())){

                            System.out.println("true");

                            platformPositonX = player1.getHitBox().getX() 
                                              + platform.getUpdateSpeed();

                            player1.action2(1, platformPositonX, 
                                           (platform.getHitBox().y +
                                           platform.getHitBox().height));

                        }else{
                            System.out.println("false");
                        }
                    }
}

Here's my print screen and my result printed in concole enter image description here As you can see my collision don't work correctly. When my character is not on the platform my result are correct I get false but when my character is on the platform i got true, false, false, true, ......


Solution

  • Finally I found out what's wrong. In this line I need to substract a number

     player1.action2(1, platformPositonX,(platform.getHitBox().y + platform.getHitBox().height - 5 ));
    

    Now all works!