sntong-Project 11: Freestyle: Playing with your Turtle(s)

sketch

// Scarlet Tong
// sntong@andrew.cmu.edu
// Section A
// Project 11: Freestyle: Playing with your Turtle(s)

// intialize global Turtle
var nTurtle;

function setup(){
  createCanvas(400,400);
  background(0);
  frameRate(60);
}


function draw(){
  // draw a new pattern when mouse is pressed located at mouseX and mouseY
if (mouseIsPressed) {

  nTurtle = new makeTurtle(mouseX,mouseY);
  // offset of lines from the center according the location of mouseX on the canvas
  var step = map(mouseX,0,width,2,40);
  // rotation of the lines stop and start at a location that is determined by mouseY
  var ratio = map(mouseY,0,height,100,150);
  // Each pattern as a maxium of 20 lines
  for (var i = 0; i < 20; i++) {
    nTurtle.setColor(color(random(255),random(100,255),random(100,255)));
    // lines function found below draw function
    lines();
    // start drawing shapes
    nTurtle.penUp();
    // offset the next lines step pixels away from the previous one
    nTurtle.forward(step);
    // rotate that new line with a set angle
    nTurtle.right(ratio);
    // end the shape
    nTurtle.penDown();
    }
  }

}


// draw lines
function lines(){
    nTurtle.setWeight(1);
    nTurtle.penDown();
    nTurtle.forward(5);
    nTurtle.penUp();
}


function turtleLeft(d){this.angle-=d;}function turtleRight(d){this.angle+=d;}
function turtleForward(p){var rad=radians(this.angle);var newx=this.x+cos(rad)*p;
var newy=this.y+sin(rad)*p;this.goto(newx,newy);}function turtleBack(p){
this.forward(-p);}function turtlePenDown(){this.penIsDown=true;}
function turtlePenUp(){this.penIsDown = false;}function turtleGoTo(x,y){
if(this.penIsDown){stroke(this.color);strokeWeight(this.weight);
line(this.x,this.y,x,y);}this.x = x;this.y = y;}function turtleDistTo(x,y){
return sqrt(sq(this.x-x)+sq(this.y-y));}function turtleAngleTo(x,y){
var absAngle=degrees(atan2(y-this.y,x-this.x));
var angle=((absAngle-this.angle)+360)%360.0;return angle;}
function turtleTurnToward(x,y,d){var angle = this.angleTo(x,y);if(angle< 180){
this.angle+=d;}else{this.angle-=d;}}function turtleSetColor(c){this.color=c;}
function turtleSetWeight(w){this.weight=w;}function turtleFace(angle){
this.angle = angle;}function makeTurtle(tx,ty){var turtle={x:tx,y:ty,
angle:0.0,penIsDown:true,color:color(128),weight:1,left:turtleLeft,
right:turtleRight,forward:turtleForward, back:turtleBack,penDown:turtlePenDown,
penUp:turtlePenUp,goto:turtleGoTo, angleto:turtleAngleTo,
turnToward:turtleTurnToward,distanceTo:turtleDistTo, angleTo:turtleAngleTo,
setColor:turtleSetColor, setWeight:turtleSetWeight,face:turtleFace};
return turtle;}

For this project I wanted to create a changing pattern that will track the mouse when it is pressed down. The pattern is drawn by the turtle graphics and has varying color.

Possible drawings to be made with the code
Drawing 2

 

Leave a Reply