Reputation: 4731
I'm completely new to JavaScript and p5.js. I know this is not the most efficient code for bouncing ball, but I tried to write my own bouncing ball mechanic as self-learning.
function draw() {
background (col); // background
col = map(cir.x, 0, 600, 0, 255) // map function
fill (350, 200, 200);
ellipse (cir.x, cir.y, cir.diameter, cir.diameter);
// Bounding ball mechanic
var speed = 3;
var hitRightWall = false;
var hitLeftWall = false;
if (cir.x >= 300) {
hitRightWall == true;
hitLeftWall == false;
}
else if (cir.x <= -50) {
hitLeftWall == true;
hitRightWall == false;
}
if (hitRightWall==true) {
speed == -3;
}
else {
speed == 3;
}
cir.x = cir.x + speed;
}
For some reason, the if (hitRightWall==True)
condition is never activated even though if (cir.x >= 300)
was activated. The ball keeps going to the right and off the screen.
Upvotes: 1
Views: 347
Reputation: 42174
There are a few things going on here. First off, you're resetting the value of hitRightWall
and hitLeftWall
to false
every frame. Is that what you want?
Secondly, look at statements like this:
hitRightWall == true;
The ==
double equals is doing a comparison, not an assignment. You probably want something like this:
hitRightWall = true;
The =
single equals assigns a value to a variable.
Finally, I'm not totally sure why you need these variables at all. Can't you modify the speed
variable directly in your first if / else if
statement?
Shameless self-promotion: here is a tutorial on collision detection. It's written for Processing, but the same ideas apply to P5.js.
Upvotes: 1