hoal
hoal

Reputation: 11

Can't make balls bounce back

I can't make the balls move in the opposite direction. Here is my code:

var xPositions = [random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400)];
var yPositions = [random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400),random(0,400)];

draw = function() {
    background(250,250, 250);
var velocidad=5;
    for (var i = 0; i < 10; i++) {

        fill(230, 156, 156);
        ellipse(xPositions[i], yPositions[i], 10, 10);
   var d=1;
   if(yPositions[i]>=400){
     d= -1;
} else if(yPositions[i]<=0){
     d = 1;
}
       yPositions[i] = yPositions[i] + velocidad*d ;
    }

};

Upvotes: 0

Views: 93

Answers (2)

Jan
Jan

Reputation: 5815

Your problem is that you're not saving the direction d each ball is traveling. In your code, once a ball reaches the edge, it will go in the opposite direction. Until it's inside the bounds again, in that loop it'll change direction again.

Which leads to the main problem with your code, having two separate arrays of x and y coordinates instead of one array of ball objects. Something like

function Ball() {
  this.x = random(0,400);
  this.y = random(0,400);
  this.direction = 1; // Or if you want to randomize: random(0,99)<50 ? -1 : 1;
  this.velocity = 5; // Or if you want to randomize: random(1, 5)
}

Ball.prototype = {
  draw:function() {
    fill(230, 156, 156);
    ellipse(this.x, this.y, 10, 10);
  },
  update:function() {
    var newposition = this.y+this.direction*this.velocity;
    if (newposition < 0 || newposition > 400) {
      this.direction*=-1; // If outside of bounds, reverse position
    }
    this.y = this.y+this.direction*this.velocity;
  }
};

Then you initiate your balls as such

var balls = [];
for (var i = 0; i < 10 ; i++){
  balls.push(new Ball());
}

And in your main loop you just need to call balls[i].update() and balls[i].draw().

draw = function() {
  for (var i = 0; i < balls.length; i++) {
    balls[i].update();
    balls[i].draw();
  }
};

There are still lots of things to be improved, but here's the gist of OOP to get you started.

Upvotes: 0

Finn
Finn

Reputation: 1056

You are setting d=1 in every iteration before you check the bounds. Move

var d=1

out of the function or out of the loop.

Upvotes: 1

Related Questions