David
David

Reputation: 3105

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, ......

Upvotes: 1

Views: 563

Answers (2)

David
David

Reputation: 3105

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!

Upvotes: 1

Angel Angel
Angel Angel

Reputation: 21728

into your sample code, just enter "false" println, if not overlaping, and touched is true, I do not know what is "touched" in this case, but if you want to enter only if, ovelaping is false, your pudes provar this:

in your code says:

..// other code

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

change for this:

..// other code

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

You might also be interested to look at this:

Libgdx - Get Intersection Rectangle from Rectangle.overlap(Rectangle)

Upvotes: 0

Related Questions