Skip to content

Instantly share code, notes, and snippets.

@nataliefreed
Created January 24, 2019 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nataliefreed/161b38a3e948ecf9b2655d40af1547df to your computer and use it in GitHub Desktop.
Save nataliefreed/161b38a3e948ecf9b2655d40af1547df to your computer and use it in GitHub Desktop.
P5.js version of turtle graphics program
// About turtle graphics: This program uses 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.
var loc; //current location
var orientation; //current orientation
var notch_height = 20;
var notch_width = 10;
function setup()
{
createCanvas(500, 500);
loc = createVector(width/2, height/2); //starting position is at center
orientation = radians(90); //starting orientation is at 90 degrees
background(255);
forward(100);
}
// Below are utility functions to calculate new positions and orientations
// when moving forward or turning. You don't need to change these.
function forward(pixels) //calculate positions when moving forward
{
start = loc;
end = p5.Vector.add(loc, polar(pixels, orientation));
line(start.x, start.y, end.x, end.y);
loc = end;
}
function left(theta) //calculate new orientation
{
orientation += theta;
}
function right(theta) //calculate new orientation
{
orientation -= theta;
}
function jumpTo(x, y) //jump directly to a specific position
{
loc = createVector(x, y);
}
function polar(r, theta) //converts an angle and radius into a vector
{
return createVector(r*cos(theta), r*sin(-theta)); // negate y for left handed coordinate system
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment