xxxxxxxxxx
80
// create class to conctruct and edit future butterflies
class Butterfly {
constructor(x, y){
this.x = x;
this.y = y;
//random starting velocity
this.xVel = random(-1, 1);
this.yVel = random(-1, 1);
}
// changing position of the butterflies depending on its velocity.
update(){
this.x += this.xVel;
this.y += this.yVel;
// Check whether the butterflies has gone off the left or right,+ move back just in case
if (this.x < 0 || this.x > width){
this.xVel = -this.xVel;
this.x += this.xVel;
}
// Check whether the butterflies has gone off the top or bottom+ move back
if (this.y < 0 || this.y > height){
this.yVel = -this.yVel;
this.y += this.yVel;
}
}
//display the butterflies on the canvas.
show(){
// triangle=butterflies coordinates, size and etc
let x1 = this.x;
let y1 = this.y - 20;
let x2 = this.x;
let y2 = this.y + 20;
let x3 = this.x + 40;
// point left if moving leftwards
if (this.xVel < 0){
x3 = this.x - 40;
}
let y3 = this.y;
//triangle- in other words butterlies
fill(224, 41, 227);
triangle(x1, y1, x2, y2, x3, y3);
}
}
let butterflies = [];
function setup(){
createCanvas(700, 700);
}
function draw(){
// background(garden);
background(69, 173, 98);
// loop over the array
for (let b of butterflies){
b.update();
b.show();
}
}
// image upload
// function preload(){
// garden = loadImage('garden.jpg');
// }
function mousePressed(){
butterflies.push(new Butterfly(mouseX, mouseY));
}