Question

I am trying to move a body with no gravity to the click or touch position and then stop it. However, depending where I click it moves really fast or really slow because of the coordinates of my Vector3. Also, it behaves like that game asteroids which I do not want.

Basically, I just need myBody follows the click of the mouse our touch.

Here where I have got so far:

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {

    camera.unproject(touchPosition.set(screenX, screenY, 0));

    Vector2 velocity = new Vector2(touchPosition.x, touchPosition.y);
    myBody.setLinearVelocity(velocity);

    return true;
}
Was it helpful?

Solution

You need to normalize and also take the position of the body itself into account. The following code is untested, but should work.

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    camera.unproject(touchPosition.set(screenX, screenY, 0));

    // calculte the normalized direction from the body to the touch position
    Vector2 direction = new Vector2(touchPosition.x, touchPosition.y);
    direction.sub(myBody.getPosition());
    direction.nor();

    float speed = 10;
    myBody.setLinearVelocity(direction.scl(speed));

    return true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top