Problems with "this.x" variable in a class

Hello, everyone!

As practice, I am working on a small sketch that has a black circle appear and move right from a black square if I hit the space bar. So far, everything looks good, but the circle isn’t moving — this.x isn’t changing even though it’s supposed to do so.

let basicDummy
let basicArray = []
let basicCount = 0

function setup() {
	createCanvas(windowWidth, windowHeight)
	background(255)
}

function draw() {
	strokeWeight(0)
	background(255)

	fill(0)
	rect(width / 4 - 20, height / 2 - 20, 40, 40) // this is the rectangle

	if (keyIsPressed) {
		if (keyCode == 32) {
			basicCount = 1
		}
	}
		
	if (basicCount == 1) {
			basicDummy = new Basic()
			basicArray[0] = basicDummy
			basicArray[0].move()
	}
}

// class below

class Basic {
	
	constructor() {
		this.x = width/4 + 30
		this.y = height/2
	}
	
	move() {
		ellipse(this.x, this.y, 20)
		this.x = this.x + 4 // THIS ISN'T WORKING
		if (this.x > width) {
			basicCount = 0
		}
	}
	
}

The reason I’m using a class is so that multiple circles can be emitted at once. If that’s not possible with my current code, please tell me.

Any help would be appreciated! :slight_smile:

1 Like

The problem is that once you hit space, you keep creating new Basic() instances each draw(), replacing the previous 1: basicArray[0] = basicDummy

Each 1 of those endless instances move() once. Obviously not enough to reach the condition if (this.x > width) {, which would reset basicCount = 0.

Also, keyIsPressed is used for when we need something to be “active” as long something is held pressed.

However, the space key in your code is supposed to be hit once each time we want another Basic instance, not continuously held down.

So you should use callback keyPressed() instead:

Here’s your code w/ some modifications I did to it:

const basicArray = []

function setup() {
  createCanvas(800, 600)
  fill(0).noStroke()
}

function draw() {
  background(255).square(width/4 - 20, height/2 - 20, 40)
  for (const b of basicArray)  b.move()
}

function keyPressed() {
  keyCode == 32 && basicArray.push(new Basic)
  return false
}

class Basic {
  constructor() {
    this.x = width/4 + 30
    this.y = height/2
    this.disabled = false
  }

  move() {
    if (this.disabled)  return
    circle(this.x += 4, this.y, 20)
    if (this.x > width)  this.disabled = true
  }
}
2 Likes

Thank you! I’m quite new to p5js and this is my first post here on the forums, so this is very helpful.