xxxxxxxxxx
62
let pArr = []; //Array storing spacePoints objects
let pNum = 600; //Default number of spacePoints when program starts. Also can be current number of spacePoints
function setup() {
createCanvas(600, 600);
for (let i = 0; i < pNum; i++) { //Generate "pNum" spacePoints on random positions and store in pArr[]
append(
pArr,
new spacePoints(random(0, width), random(0, height))
);
}
}
function draw() {
background(0);
for (let i = 0; i < pNum; i++) {
pArr[i].movePoint(); //Update positions of spacePoints in pArr
pArr[i].drawPoint(); //Draw spacePoints in pArr on the canvas
}
}
function mouseClicked() { //When mouse is clicked
append(pArr, new spacePoints(mouseX+random(-5,5), mouseY+random(5,-5))); //Generate new spacePoint at where the mouse is clicked. Store it in pArr[]
pNum++; //Increase number of current number of spacePoints by 1
}
class spacePoints { //Declare class
constructor(posX, posY) {
this.posX0 = posX; //Original X coordinate of the point
this.posY0 = posY; //Original Y coordinate of the point
this.posX = posX; //Current X coordinate
this.posY = posY; //Current Y coordinate
this.color = 255; //Color of the point when drawn
}
movePoint() { //Moves spacePoints away from the mouse. spacePoints moves faster when the cursor is closer. spacePoint returns to its intital position when cursor is away
let cursorDist = dist(this.posX, this.posY, mouseX, mouseY); //Distance between a spacePoint and the cursor
if (cursorDist < 100) { //If cursorDist is less then 0, move spacePoints away from the cursor
let dVec = createVector(this.posX - mouseX, this.posY - mouseY); //Create a vector connecting a spacePoint and the cursor
dVec = dVec.setMag(100 / dVec.mag()); //Magnitude of dVec is inversly proportional to cursorDist
this.posX += constrain(dVec.x, -20, 20); //Move a spacePoint based on dVec
this.posY += constrain(dVec.y, -20, 20);
this.color = 0; //Set color value to 0 when a spacePoint is in motion
} else {
if (abs(this.posX - this.posX0) > 1 || abs(this.posY != this.posY0) > 1) { //When a spacePoint is not in its inital position
let dVec = createVector(this.posX0 - this.posX, this.posY0 - this.posY);
dVec.setMag(1);
this.posX += dVec.x; //Move a spacePoint toward its initial position
this.posY += dVec.y;
}else this.color=255; //Reset color value
}
}
drawPoint() { //Draw a spacePoint
noFill();
stroke(this.color,125,125);
strokeWeight(3);
circle(this.posX, this.posY, 8);
}
}