Set up wraparound effect in libGDX with Box2D

335 views Asked by At

i have been having trouble trying to set up wraparound in LibGDX using box2D, for example i want my player to appear at the left side of the screen after exiting the right side, but its not working here is my code:

public void setWraparound(){
    //if player goes out of bounds vertically
    if(body.getPosition().x < 0){
        body.setTransform(new Vector2(4.8f, body.getPosition().y),body.getAngle());
    }else if(body.getPosition().x > 4.8f){
        body.setTransform(new Vector2(0, body.getPosition().y), body.getAngle());
    }

    //if player goes out of bounds Horizontally
    if(body.getPosition().y < 0){
        body.setTransform(new Vector2(body.getPosition().x,8f), body.getAngle());
    }else if(body.getPosition().y > 8f){
        body.setTransform(new Vector2(body.getPosition().x,0), body.getAngle());
    }

}

Then i call the method in my GameStage class like this:

 public GameStage() {
    setUpWorld();
    setupCamera();
    setupTouchControls();
    player.setWraparound();
    renderer = new Box2DDebugRenderer();
}

anyone to help me out?

1

There are 1 answers

3
donfuxx On BEST ANSWER

The place where you call your setWraparound method is wrong. You need to call it after a collision of the player with screen border happens. I suggest you do the following

  1. Create static bodies for each screen border (you could use for example EdgeShape for that)
  2. Add a ContactListener to your box2D world and check in the beginContact method if player & wall do touch.
  3. Now after touch was detected call your method setWraparound

Alternatively you could create a Sensor that matches the screen size and detect if player touches the sensor borders. Or you could just check every frame your player's x/y positions and see if they are out of the screen, but it is better to use box2D collision detection.