Search code examples
javaandroidlibgdxontouchlistenerontouch

Libgdx Character Movement


I have recently jumped into Libgdx. My ontouch is only half working; I know the touch is being detected as when I run the below:

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
player.b2body.applyLinearImpulse(new Vector2(5.1f, 0), player.b2body.getWorldCenter(), true);

        return true;
    }

My character does run to the right, thus proving my on touch is setup correct and is being detected.

The issue I am having is getting the character to run left or right depending on where on the screen the user touches down on. If the user presses to the right the character needs to move right and if pressing to the left of the character it should move left, on the x axis. What I have written to do this is below:

@Override
public boolean touchDown(int X, int Y, int pointer, int button) {

 //   player.b2body.applyLinearImpulse(new Vector2(5.1f, 0), player.b2body.getWorldCenter(), true);
    if(  player.getX()> X ){
        player.b2body.applyLinearImpulse(new Vector2(5.1f, 0), player.b2body.getWorldCenter(), true);
    }

    else if(  player.getX()< X ){
        player.b2body.applyLinearImpulse(new Vector2(-5.1f, 0), player.b2body.getWorldCenter(), true);
    }
    return true;
}

But with my code my character does not move, I presume I am checking the players position on incorrectly. Can anyone please advise on what/ how I'm doing this wrong?


Solution

  • Touch positions are given in screen coordinates. Your player exists in whatever world coordinates you created. You need to use Camera.unproject to convert from screen coords to world coords using your camera.