Skip to content

Instantly share code, notes, and snippets.

@nataliefreed
Last active June 6, 2020 10:39
Show Gist options
  • Save nataliefreed/8483050 to your computer and use it in GitHub Desktop.
Save nataliefreed/8483050 to your computer and use it in GitHub Desktop.
Turtle Graphics in Processing: This program shows another way to think about moving through Processing's coordinate system, inspired by Logo. Instead of placing points on a grid, you can imagine yourself as being somewhere on the grid, facing a direction. You can move forward or turn. The drawn line follows behind you.
// Turtle Graphics in Processing
// Natalie Freed, February 2013
// This program shows another way to think about moving
// through Processing's coordinate system. Instead of placing
// points on a grid, you can imagine yourself as being somewhere
// on the grid, facing a direction. You can move forward or turn.
// The drawn line follows behind you.
PVector loc; //current location
float orientation; //current orientation
void setup()
{
size(500, 500);
loc = new PVector(width/2, height/2); //starting position is at center
orientation = radians(90); //starting orientation is at 90 degrees
}
void draw() //this example draws a polygon. Can you change the number of sides?
{
forward(50); //go forward 200 pixels
left(radians(30)); //turn 30 degrees to the left
//repeat
}
// Below are utility functions to calculate new positions and orientations
// when moving forward or turning. You don't need to change these.
void forward(float pixels) //calculate positions when moving forward
{
PVector start = loc;
PVector end = PVector.add(loc, polar(pixels, orientation));
line(start, end);
loc = end;
}
void left(float theta) //calculate new orientation
{
orientation += theta;
}
void right(float theta) //calculate new orientation
{
orientation -= theta;
}
void jumpTo(int x, int y) //jump directly to a specific position
{
loc = new PVector(x, y);
}
void line(PVector a, PVector b) //new line function with PVectors. used by forward function
{
line(a.x, a.y, b.x, b.y);
}
PVector polar(float r, float theta) //converts an angle and radius into a vector
{
return new PVector(r*cos(theta),r*sin(-theta)); // negate y for left handed coordinate system
}
@heerdyes
Copy link

heerdyes commented Apr 7, 2020

neat!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment