GAME DESIGN IN LIBGDX

GUIDE – MOVABLE IMAGE

separator-blank.png

DESCRIPTION

This basic code simply uses the Still Image code from the previous example and shows how to make the image move using the arrow keys.

CODE

public class MovableImageDemo extends ApplicationAdapter

{

   private SpriteBatch batch;

   private Texture texture;

   private Sprite sprite;

  

   private float shipX;

   private float shipY;

 

   @Override

   public void create ()

   {

      batch = new SpriteBatch();

      texture = new Texture(Gdx.files.internal("blueship64.png"));

      sprite = new Sprite(texture);

     

      shipX = 100;

      shipY = (Gdx.graphics.getHeight() - 64) /2;  //64 is img height

   }

 

   @Override

   public void dispose()

   {

       batch.dispose();

       texture.dispose();

   }  

  

   @Override

   public void render()

   { 

         //UPDATE

         if(Gdx.input.isKeyPressed(Input.Keys.UP))

         {

               shipY = shipY + 5;

         }

         if(Gdx.input.isKeyPressed(Input.Keys.DOWN))

         {

               shipY = shipY - 5;

         }

         if(Gdx.input.isKeyPressed(Input.Keys.LEFT))

         {

               shipX = shipX - 5;

         }

         if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))

         {

               shipX = shipX + 5;

         }

        

       //Clear screen

         Gdx.gl.glClearColor(0, 0, 0, 1);

         Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        

       //Render

       batch.begin();

       sprite.setPosition(shipX, shipY);

       sprite.draw(batch);

       batch.end();

   }

}


JAR FILE

Click here.


separator-campeau.png