Link Search Menu Expand Document

Drawing a Line

Now that you can move, let’s draw! The spiral image on the previous page is made up of lines and only lines! To start drawing, you need to know how to draw a line using a little bit of Java code in the Greenfoot environment.

To get the drawing to work, we need to write a method that will move and draw a line at the same time. Here is that method along with the modification to the act() method.

NOTE: You don’t need to worry about the details of the moveAndDraw() method below, just know that it does the same thing as the move() method before while drawing a line along the way. We are abstracting away the details.

/**
 * MoveAndDraw – This function draws a line while moving.
 */
private void moveAndDraw(int distance)
{
    getWorld().getBackground().setColor(Color.BLACK);
    final int X_VECTOR = (int)(getX() + distance * Math.cos(Math.toRadians(getRotation())));
    final int Y_VECTOR = (int)(getY() + distance * Math.sin(Math.toRadians(getRotation())));
    getWorld().getBackground().drawLine(getX(), getY(), X_VECTOR, Y_VECTOR);
    move(distance);
}

/**
 * Act – do whatever the Turtle wants to do. This method is called whenever
 * the ‘Act’ or ‘Run’ button gets pressed in the environment.
 */
public void act()
{
    // Add your action code here
    moveAndDraw(50);
}
  • Don’t forget to “compile” your code in the editor before clicking > Act in the scenario!
  • Note the increase in pixels from 10 to 50 in the act() method. Try changing the number in the line moveAndDraw(50), execute the code again, and see what happens.