Using mousePressed to place different indexes of an array on the canvas

Hello Reaching out for some help,

What I am trying to do is when I press mouse button a different part of an array is show and placed on the screen, what is happening is that even though the selected array index is the one being shown once I change the array pressing β€œc” all of the objects placed already on the canvas change.

My final goal is to have a letter, click to place it down, change the letter, place it somewhere else, etc.

let tx = ["A", "B", "C", "D", "E", "8", "9", "1"];

class Bubbles {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  preview() {
    push();
    translate(mouseX, mouseY);
    text(tx[z], 0, 0);
    pop();
  }

  show() {
    textSize(100);
    textAlign(CENTER, CENTER);
    text(tx[placed], this.x, this.y);
  }
}

let bubble = [];
let z = 0;
let placed = 0;
let targetX;
let targetY;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(255);
  for (let i = 0; i < bubble.length; i++) {
    bubble[i].preview();
    bubble[i].show();
  }
}

function mouseClicked() {
  let b = new Bubbles(mouseX,mouseY);
  bubble.push(b);
  targetX = mouseX;
  targetY = mouseY;
  placed = z; 
  
}

function keyPressed() {
  if (key == "c") {
   z++;
    if (z == tx.length) {
      z = 0;
    }
  }
}

Thank you in advance, if there is anything else I can provide to explain please let me know.

Thank you.

1 Like

Your global variable placed determines the current index for the global array tx[].

So when you change placed’s value all instances of class Bubbles also changes along:
text(tx[placed], this.x, this.y);

1 Like

The reason that I used the placed variable is so I could change the letter that follows my cursor the β€œpreview” letter without changing the one that is already placed down. But its still changing it.
when I click or sometimes when I press β€œc”, depending on where I declared the variable. Putting it as a global variable was the closes I got to having the preview and the one placed different from each other at least until any other action was done.

I am stuck on this one and I feel like I need another variable or may need to go into this a whole different way, without using objects.

Apart from turning the computer off and burning the hard drive, any suggestions ?

You can make your class record which character to display at the moment you instantiate it:

bubbles.push(new Bubble(mouseX, mouseY, tx[placed]));

class Bubble {
  constructor(x, y, ch) {
    this.x = x;
    this.y = y;
    this.ch = ch;
  }

    text(this.ch, this.x, this.y);

}
1 Like

THANK YOU VERY MUCH!,

This was the solution, I appreciate you taking the time to help me.