Drawing text - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki

The text() function allows us to draw text on the screen at a certain pixel location.

For example we can draw the robot's x and y co-ordinates in the top left of the screen.

function draw() {
  text(robotX, 5, 15);
  text(robotY, 5, 30);
}

String concatenation

We can combine strings together, for example we may want to indicate on the screen at the robotX value is in fact the x co-ordinate. We can combine strings (or concatenate them) using the + operator. For example:

var label = "x: " + robotX;

The variable label will now contain the string "x: 115" (if robotX has the value 115).

We can insert this directly into our text() call:

function draw() {
  text("x: " + robotX, 5, 15);
  text("y: " + robotY, 5, 30);
}

Debugging

Drawing text on the screen can be useful for debugging. If the program isn't operating as expected you can draw values of variables to get an insight as to what is happening in a program.