I am making a ball class, and in that class i want to make the ball bounce off the wall, but it remains stuck.
I have tried making the ball bounce in the draw function, but then it didnt even stopped at the wall. I tried setting the this.x and this.y away from the limit so it doesnt loop, but no succes. I am left without choises. I dont know what to do. I am just starting out and im quite enjoying coding, but this is giving me a headache.
let r;
let g;
let b;
let xpos;
let ypos;
let size;
let xlimit;
let ylimit;
let x_limit;
let y_limit;
let xspeeddir;
let yspeeddir;
function setup() {
createCanvas(800, 450);
xpos = random(20, width);
ypos = random(20, height);
ball = new Ball(xpos, ypos);
xlimit = width-15;
ylimit = height-15;
x_limit = 15;
y_limit = 15;
r = random(0, 255);
g = random(0, 255);
b = random(0, 255);
xspeeddir = random(-5,5);
yspeeddir = random(-5,5);
}
function draw() {
background(255, 238, 112);
ball.appear(r, g, b);
ball.move(xspeeddir, yspeeddir);
}
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = 30;
}
appear(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
fill(this.r, this.g, this.b);
noStroke();
ellipse(this.x, this.y, this.size, this.size);
}
move(xspeed, yspeed) {
this.speedx = xspeed;
this.speedy = yspeed;
if (this.x > xlimit) {
this.speedx = -Math.abs(this.speedx);
this.x = xlimit-1;
}
if (this.x < x_limit) {
this.speedx = Math.abs(this.speedx);
this.x = x_limit + 1;
}
if (this.y > ylimit) {
this.speedy = -Math.abs(this.speedy);
this.y = ylimit - 1;
}
if (this.y < y_limit) {
this.speedy = Math.abs(this.speedy);
this.y = ylimit + 1;
}
this.x = this.x + this.speedx;
this.y = this.y + this.speedy;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
No errors in the console