Transparent Shells

An example of adding functionality to turtles and working with instances

Log in to post a comment.

Canvas.setpenopacity(.2)

// adding some functionality to Turtle
Turtle.prototype.currentPos = [0, 0]
Turtle.prototype.currentAngle = 0
Turtle.prototype.move = function(forward, right) {
    this.forward(forward)
    this.right(right)

    angleRadians = Math.PI * 2 * this.currentAngle / 360
    this.currentPos[1] += forward * Math.sin(angleRadians)
    this.currentPos[0] += forward * Math.cos(angleRadians)
    this.currentAngle += right
}
Turtle.prototype.jump1 = function(x, y) {
    this.penup()
    this.goto(x, y)
    this.pendown()
    
    this.currentPos = [x, y]
}

// defining an object that has its own turtles
function Shell (angle, alternation, range, startX, startY, startAngle) {
    this.turtle = new Turtle()
    this.line = new Turtle()
    
    this.turtle.move(0, startAngle)
    this.turtle.jump1(startX, startY)
    
    this.walk = function(i) {
        newAngle = i % alternation > alternation / 2 ? angle : -angle
        this.turtle.move(2, newAngle)
        this.line.jump1(startX, startY)
        this.line.goto(this.turtle.currentPos[0], this.turtle.currentPos[1])
        
        return i < range
    }
    
    this.getPosition = function() {
        return this.turtle.currentPos
    }
}


// instancing the object
const angleRange = 10
const positionRange = 100
const numShells = 60

shells = []
for (i = 0; i < numShells; i++) {
    shells[i] = new Shell(
        20 + angleRange * rand(),
        10, 
        90 + rand() * 90,
        positionRange * rand(),
        positionRange * rand(),
        rand() * 360
        )
}

// applying walk to all objects
function walk(i) {
    shells = shells.filter(shell => shell.walk(i))
    return shells.length > 0
}

function rand() {
    return Math.random() * 2 - 1 
}