0

So i am a begginer at coding. Ive watched a few vids of coding train about the p5.js library and now im trying to make a class named "Ball", that when it hits the wall, it changes direction. But it just gets blocked in a corner

I have tried making the position to change outside of the class, in the draw function, but then it doesnt even stop at the edges

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

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 = -(this.speedx)
    }

    if (this.x <= this.size/2) {
        this.speedx = -(this.speedx)
    }

    if (this.y >= ylimit) {
        this.speedy = -(this.speedy)
    }

    if (this.y <= this.size/2) {
        this.speedy = -(this.speedy)
    }

    this.x = this.x + this.speedx;
    this.y = this.y + this.speedy;
}
}

I dont get any errors in the console.

  • Make sure that you initialize the ball inside of the limits – Jonas Wilms Jul 06 '19 at 17:57
  • It is initialized inside. I tried using the absolute value, didnt work. I got an suggestion saying i should set this.x = xlimit if it passes the boundary and then reverse its speed. That didnt work either. i dont know what to do. – Stefan122GG Jul 06 '19 at 21:46
  • Possible duplicate of [I have been trying to make this ball bounce for a day. Why doesnt it work?](https://stackoverflow.com/questions/56921213/i-have-been-trying-to-make-this-ball-bounce-for-a-day-why-doesnt-it-work) – Rabbid76 Jul 07 '19 at 10:39

1 Answers1

0

If the ball is far outside from its territory, then it'll inverse its direction, so if it is far too right it'll go left, however on the next tick, it is still far too right, then the direction will be inversed again, and it goes a bit to the right, so it doesn't get into the range again. So this.speedx = -(this.speedx) is generally a dangerous thing to do, I'd rather do:

  this.speedx = - Math.abs(this.speedx)

or

 this.speedx = Math.abs(this.speedx)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151