Search code examples
androidlibgdxtextures

libGDX: smooth movement if justTouched


I want to check if the touchscreen is touched and move the position of my texture. With the check input.isTouched() it works well and i get a smooth movement of my texture while my touchscreen is touched.

public void update() {
   if(input.isTouched()){
      x += 60 * Gdx.graphics.getDeltaTime()
   }
}

public void render(SpriteBatch batch){
   batch.begin();
   batch.draw(texture, x, y); 
   batch.end();
} 

Now I want to implement the movement of my texture when input.justTouched(). In this case my texture will move in only one frame when i'm doing x += 600;. My idea is a second render method in my render method, but i think that's not efficient and honestly i don't really know how it works.


Solution

  • if(Gdx.input.isTouched()){    // condition true when screen is currently touched.
        x += 60 * Gdx.graphics.getDeltaTime();
    }
    

    So somehow we need to maintain condition/flag true for required number of frame to reach destination that is 600 in your case.

    Having many possible solution to achieve this, and the simplest is :

    public class GdxTest extends ApplicationAdapter {
    
       Texture texture;
       SpriteBatch spriteBatch;
       float x,y,endX;
    
       @Override
       public void create() {
    
          texture=new Texture("badlogic.jpg");
          spriteBatch=new SpriteBatch();
          y=20;
          x= endX=10;
       }
    
       @Override
       public void render() {
    
          Gdx.gl.glClearColor(1,1,1,1);
          Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    
          spriteBatch.begin();
          spriteBatch.draw(texture,x,y);
          spriteBatch.end();
    
          if(Gdx.input.justTouched()){   // when new touch down event just occurred.           
            endX=600;  // give destination
          }
    
          if(x<endX){    // this condition will true unless x reaches endX or crossed
            x+=60 * Gdx.graphics.getDeltaTime();
          }
       }
    
       @Override
       public void dispose() {
           texture.dispose();
           spriteBatch.dispose();
       }
    }