Search code examples
javaandroidlibgdx

Android/Libgdx How to fix this issue?


Currently iam programming on a game where you move a spaceship and try to avoid asteroids. The spaceship should move when the user touches it and so follow the finger movement of the user. The spaceship is a sprite that moves arround with:

if (Gdx.input.isTouched()) {  

    x = Gdx.input.getX() - width / 2;
    y = -Gdx.input.getY() + height / 2;

} 

The problem that i'm having right now is that the user can teleport the spaceship by touching the screen. How can i fix this? Is it possible to set a touch region?


Solution

  • Calculate a unit vector direction from the ship to the touch point and multiply that by a speed. You need to convert touch coordinates to world coordinates by unprojecting with the camera.

    private static final float SHIP_MAX_SPEED = 50f; //units per second
    private final Vector2 tmpVec2 = new Vector2();
    private final Vector3 tmpVec3 = new Vector3();
    
    //...
    
    if (Gdx.input.isTouched()) {  
        camera.unproject(tmpVec3.set(Gdx.input.getX(), Gdx.input.getY(), 0)); //touch point to world coordinate system.
        tmpVec2.set(tmpVec3.x, tmpVec3.y).sub(x, y); //vector from ship to touch point
        float maxDistance = SHIP_MAX_SPEED * Gdx.graphics.getDeltaTime(); //max distance ship can move this frame
        if (tmpVec2.len() <= maxDistance) {
            x = tmpVec3.x;
            y = tmpVec3.y;
        } else {
            tmpVec2.nor().scl(maxDistance); //reduce vector to max distance length
            x += tmpVec2.x;
            y += tmpVec2.y;
        }
    }