Search code examples
javaandroidlibgdx

Move rectangle by touching the screen


I want to move blocks with different x-positions without changing their shape by reducing the x-position.

I have tried to run the following code, but it seems like the blocks move to a tow position way to fast (correct potion and other i can't see where).

downBlocks=new Arraylist<Rectangle>;
for (DownBlocks downBlocks:getBlocks()){
    if(Gdx.input.isTouched()) {
        Vector3 touchPos = new Vector3();

        touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        camera.unproject(touchPos);

        downBlocks.x = (int) touchPos.x - downBlocks.x;
    }
}

Solution

  • To do a drag, you need to remember the point where the finger last touched the screen so you can get a finger delta. And as a side note, avoid putting code inside your loop iteration if it only needs to be called once. It's wasteful to unproject the screen's touch point over and over for every one of your DownBlocks.

    static final Vector3 VEC = new Vector3(); // reusuable static member to avoid GC churn
    private float lastX; //member variable for tracking finger movement
    
    //In your game logic:
    if (Gdx.input.isTouching()){
        VEC.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        camera.unproject(VEC);
    }
    
    if (Gdx.input.justTouched())
        lastX = VEC.x; //starting point of drag
    else if (Gdx.input.isTouching()){ // dragging
        float deltaX = VEC.x - lastX; // how much finger has moved this frame
        lastX = VEC.x; // for next frame
    
        // Since you're working with integer units, you can round position
        int blockDelta = (int)Math.round(deltaX);
    
        for (DownBlocks downBlock : getBlocks()){
            downBlock.x += blockDelta;
        }
    }
    

    I don't recommend using integer units for your coordinates, though. If you are doing pixel art, then I recommend using floats for storing coordinates, and rounding off the coordinates only when drawing. That will reduce jerky-looking movement. If you are not using pixel art, I would just use float coordinates all the way. Here's a good article to help understand units.