Functions to Draw Characters
Functions to Draw Characters
In the first course project, students wrote a sequence of code statements to draw and color shape primitives to create a 2D character. In order to improve our code, we want to make it more modular - so we'll break-down our code logic into functions.
In addition, we'll use the Processing transform functions to translate the origin to our character's center point, as a first step in thinking about how we'll eventually animate the character.
Example: Turtle
In the following description, we'll look at how to write code to create a simple turtle - using functions to specify the overall turtle's design, with additional functions that define the subcomponents of the turtle, like the head or feet.
Example 1: One function for drawTurtle( x, y ) - In the first code example, we're putting all of the code in a single function. We are going to use pushMatrix(), popMatrix() to isolate the rest of our code from any transforms that we do within those push/pop regions.
Example 1: Turtle in a Single Javascript Function
Example 2: Several functions within drawTurtle( x, y); It's not much more difficult to put the logic for the turtle's parts: head and foot, into their own functions, plus it will make our code more structured.
Example 2: Turtle using multiple functions
DrawTurtle Logic - Using multiple functions:
The code below is the main function to create the turtle. Within this function, other functions are called to create his sub-components. The subcomponents, like feet and head have a dependency on the turtle body, whenever the body moves, the head and feet should also move. This dependency is implemented by calling the drawHead, drawFoot functions after translate( x,y) has moved the origin to the turtle's center point.
Calling the drawTurtle Function
The code below shows how to call the drawTurtle function within the Processing draw( ) function by passing in parameter values that have been declared as global variables. Eventually, we'll be able to animate the turtle by modifying the value of these global variables in the draw loop.
We can see that the animation variables are passed directly into the drawTurtle function, then they will be passed into each of the functions where they are controlling animation.
DrawHead( ) and DrawFoot functions
Last updated