xxxxxxxxxx
87
let canvas;
let h1;
let a=200;
let b=200;
let balls = [];
function mousePressed(){
createP("Working on html")
h2.html('Now I will show you my favorite color')
}
function setup() {
canvas= createCanvas(400, 400);
canvas.position(0,0);
h1=createElement('h1','my favorite color is purple');
h2=createElement('h2','Waiting')
// h1.position(100,100);
h2.position(100,200);
// createP("Working on LALALAL")
// ball1=new Ball(width/2,height/2);
for (let i = 0; i < 20; i++) {
balls[i] = new Ball(random(width), random(height), random(100))
}
}
function draw() {
background(0);
clear();
fill('blue');
ellipse(a,b,50,50);
h1.position(a,b);
a=a+random(-5,5);
for (let i = 0; i < balls.length; i++) {
balls[i].display();
balls[i].bounce();
for (let j = i+1; j < balls.length; j++) {
if (balls[i].collide(balls[j])) {
balls[i].changeCol();
balls[j].changeCol();
}
}
}
}
class Ball {
constructor(tempX, tempY, tempD = 10, tempXvel = 1, tempYvel = 2, tempCol = color(255, 255, 255),tempColChanged=false) {
this.x = tempX;
this.y = tempY;
this.d = tempD;
this.xVel = tempXvel;
this.yVel = tempYvel;
this.col = tempCol;
this.colChanged=tempColChanged;
}
display() {
fill(this.col);
noStroke();
circle(this.x, this.y, this.d);
}
bounce() {
this.x += this.xVel;
this.y += this.yVel;
if (this.x < this.d / 2 || this.x > width - this.d / 2) {
this.xVel *= -1;
}
if (this.y < this.d / 2 || this.y > height - this.d / 2) {
this.yVel *= -1;
}
}
collide(other){
let distance=dist(this.x,this.y,other.x,other.y);
return(distance<this.d);
}
changeCol(){
if(this.colChanged){
this.col=color("red");
}else{
this.col=color("white");
}
this.colChanged=!this.colChanged;
}
}