Turtle Graphics

james-turtlegraphicscompostion

//James Katungyi
//Section A 0900
//jkatungy@andrew.cmu.edu
//Assignment-Project-11

var timer = 0.01;
var inc = 0.001;
//turtle graphics
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(200),
                  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;
}
//using turtle graphics to draw cloudy sin curve using perlin noise
function setup(){
    createCanvas(600, 400);
    background(250, 50);
}

function draw(){
    var amplitude = 50 + timer * noise(inc);
    var startVal = 50 + timer * noise(inc);
    var myTurtle = makeTurtle(0, startVal);
    for (var x = 0; x < width; x++){
        //restrict sin curve within the canvas edges
        var angle = map(x, 0, width, 0, TWO_PI);
        //sin curve
        var yLoc = startVal + sin(angle) * amplitude;
        myTurtle.goto(x, yLoc);
    }
    timer++;
    inc++;

    if (frameCount%400 == 0){
        background(250);
    }
}

I wanted to use the turtle to draw a sin curve that gently distorts over time leaving a soft mesh in its wake similar to the image below. I lost control of the turtle stroke and perlin noise, then ran out of time. Will explore more after.

cloudy

Leave a Reply