How in the world does one isolate part of a class used in an array?
So I’ve started using class() for defining objects, got it. And now let’s put those objects into an array, no problem got it. Now let’s make it so they all move independently of each other….don’t got it.
move() { if ((this.x > width) || (this.x < 0)) { speedx = speedx * -1; } this.x = this.x + speedx; if ((this.y > height) || (this.y < 0)) { speedy = speedy * -1; } this.y = this.y + speedy; // this.y = slider_speedY.value() }
See here is the problem, the block of code is pretty straight forward, when used on one object no problem however, if that object is in an array the issue rears it’s evil little head. When any of the objects in the array meet the criteria for this.x or this.y the value is inverted because it is multiplied by -1. So instead of each object independently meeting the criteria and changing the value by (*-1), ALL objects in the array are assigned this value at the same time. How can the object only be effected by the condition logic in the aforementioned block of code only when that object meets the criteria?
Here is the code in it’s entirety
let speedx = 3; let speedy = 5; let speedx1 = 2; let speedy1 = 1; let squares = []; let spots = []; function setup() { createCanvas(600, 600); frameRate(10); } function mousePressed() { if (random(1) < 0.5) { let s = new Square(mouseX, mouseY, 50, 50, 5); squares.push(s); } else { let s2 = new Spot(mouseX, mouseY, 50, 50); spots.push(s2); } } function draw() { background(0); for (let square of squares) { // push(); square.show(); square.move(); // pop(); for (let i = 0; i < squares.length; i++) { squares[i].move(); squares[i].show(); } } for (let spot of spots) { // push(); spot.show(); spot.move(); // pop(); for (let i = 0; i < spots.length; i++) { spots[i].move(); spots[i].show(); } } } class Square { constructor(tempX, tempY, tempH, tempW) { this.x = tempX; this.y = tempY; this.h = tempH; this.w = tempW; } move() { if ((this.x > width) || (this.x < 0)) { speedx = speedx * -1; } this.x = this.x + speedx; if ((this.y > height) || (this.y < 0)) { speedy = speedy * -1; } this.y = this.y + speedy; } show() { push(); rectMode(CENTER); stroke(255); strokeWeight(1); noFill(); rect(this.x, this.y, this.w, this.h); pop(); // p;rint(this.x); } } class Spot { constructor(spotX, spotY, spotH, spotW) { this.x = spotX; this.y = spotY; this.h = spotH; this.w = spotW; } move() { push(); if ((this.x > width) || (this.x < 0)) { speedx1 = speedx1 * -1; } this.x = this.x + speedx1; if ((this.y > height) || (this.y < 0)) { speedy1 = speedy1 * -1; } this.y = this.y + speedy1; pop(); } show() { // push(); ellipseMode(CENTER); stroke(255, 0, 0); strokeWeight(1); noFill(); ellipse(this.x, this.y, this.h, this.w); // pop(); // print(this.x); } }
Here is a link to the working sketch