xxxxxxxxxx
92
function angle2xy(angle, r){
print(angle, r)
return [r*cos(angle), r*sin(angle)]
}
function xy2angle(x,y){
return atan2(y,x)
}
function step(current, target, speed){
if (current < target){
current = current + min(speed, target - current)
} else if (current > target) {
current = current - min(speed, current - target)
}
return current
}
class Segment{
constructor(x=0,y=0,rad=30){
this.x = x
this.y = y
this.rad = rad
this.angle = 0
}
draw(){
circle(this.x, this.y, this.rad)
}
}
class Snake{
constructor(x=0, y=0, pieces = 4, rad=30){
this.x = x
this.y = y
this.pieces = pieces
this.rad = rad
this.targetX = 0
this.targetY = 0
this.angle = 0
this.linSpeed = 5
this.angSpeed = 0.5
this.segments = []
for(let i = 0; i<pieces; i++){
this.segments.push(new Segment(this.x, this.y, this.rad))
}
}
updateTarget(mouseX, mouseY){
this.targetX = mouseX
this.targetY = mouseY
}
update(){
//placeholder code
// this.x = this.targetX
// this.y = this.targetY
// slowly change the position and angle of the snake
let targetAngle = xy2angle(this.targetX - this.x, this.targetY - this.y)
this.angle = step(this.angle, targetAngle, this.angSpeed)
let pt = angle2xy(this.angle, this.linspeed)
this.x = step(this.x, pt[0], this.linSpeed)
this.y = step(this.y, pt[1], this.linSpeed)
//update the position of all the segments
this.segments[0].x = this.x
this.segments[0].y = this.y
for (let i = 1; i<this.segments.length;i++){
let pt = angle2xy(this.segments[i].angle, this.segments[i].rad)
this.segments[i].x = this.segments[i-1].x + pt[0]
this.segments[i].y = this.segments[i-1].y + pt[1]
}
}
draw(){
this.update()
fill(255)
noStroke()
for (let i=0; i<this.segments.length; i++)
this.segments[i].draw()
}
}
snake = new Snake()
function setup() {
createCanvas(windowWidth, windowHeight);
angleMode(DEGREES)
}
function draw() {
background(0);
snake.updateTarget(mouseX, mouseY)
snake.draw()
}