5 – DRAWING WITH LIBGDX

 

 

COORDINATE SYSTEM

 

In LibGDX, the origin (0,0) is at the bottom left.   As you move right, x increases.  As you move up, y increases.  This is similar to what you would do in a math course.   Note that this is different than with NOOPDraw.

 

THE SHAPERENDERER CLASS

 

The ShapeRenderer class provides us with the ability to render simple shapes (outlines or filled shapes) onto the screen.  We will look at a few simple examples below.

 

EXAMPLE 1 – A SIMPLE SQUARE

 

In this example, we will go step by step through the process of drawing a simple square on the screen.

 

First off, we need to declare a ShapeRenderer object as a datafield.   Then, inside the create method, we need to create this object.  Here is the code so far:

 

   ShapeRenderer shapeRenderer;

 

   public void create ()

   {

       shapeRenderer = new ShapeRenderer();

   }

 

Now in the render method, we simply need to specify the details of the shape we want.  We start by using the begin method and end with the end method. Between those statements, we simply see the colour and draw a rectangle at (10, 10) with a height of 100 and a width of 100.

 

   public void render ()

   {

      shapeRenderer.begin(ShapeType.Filled);

      shapeRenderer.setColor(Color.WHITE);

      shapeRenderer.rect(10, 10, 100, 100);

      shapeRenderer.end();

   }

 

Here is the full code and the result of it:

 

public class PongGame extends ApplicationAdapter

{

   ShapeRenderer shapeRenderer;

 

   @Override

   public void create ()

   {

       shapeRenderer = new ShapeRenderer();

   }

 

   @Override

   public void render ()

   {

      shapeRenderer.begin(ShapeType.Filled);

      shapeRenderer.setColor(Color.WHITE);

      shapeRenderer.rect(10, 10, 100, 100);

      shapeRenderer.end();

   }

}

The result:

 

EXAMPLE 2 – A FEW SHAPES

 

The code below will create the different shapes seen in the image.

 

public class PongGame extends ApplicationAdapter

{

   private ShapeRenderer renderer;

 

   @Override

   public void create()

   {

       renderer = new ShapeRenderer();

   }

 

   @Override

   public void render()

   {

      renderer.begin(ShapeType.Filled);

      renderer.setColor(Color.RED);

      renderer.rect(25, 10, 300, 400);

     

      renderer.setColor(255,0,255,0.5f);  //purple

      renderer.triangle(240,50,405,340,620,70);

     

      renderer.setColor(0,0,255,0.5f);

      renderer.circle(500, 330, 75);

     

      renderer.end();

   }

}

The result: