Instantly share code, notes, and snippets.

nataliefreed/turtle.js

Created January 24, 2019 13:49
Star You must be signed in to star a gist
P5.js version of turtle graphics program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 // 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 }