problem with Object array's size

edited October 2013 in Questions about Code

Hi , I've got a strange problem with my code :

it's one of Nature of Code (Forces section) sketches , I just made an array of these Spheres . it works fine with 10 as arraylength but when i make it more than 10 the circles get crazy movements !

the Code :

Sphere[] spheres;

void setup(){
 // frameRate(60);
  size(800,720);
//  smooth();
  spheres = new Sphere[10];
  for (int i=0;i< spheres.length ; i++){
  spheres[i] = new Sphere();
  }
}



void draw(){
  background(255);
  PVector gravity = new PVector(0,0.2);
  PVector wind = new PVector(0.3,0);

  for(Sphere s:spheres){
  gravity.mult(s.mass);

  s.applyForce(gravity);

  if(mousePressed){
  s.applyForce(wind);
  }

  s.update();
  s.display();
  s.checkEdges();

  }  
}

class Sphere {
 PVector location ;
 PVector velocity ;
 PVector acceleration ;
 float mass ;
 color c ;
 float topSpeed ;
 float radius ;


Sphere (){
 location = new PVector (random(width), random(height/2));
 velocity = new PVector (0,0);
 acceleration = new PVector (0,0);
 mass = random (.5 , 4);
 c = color (random(255));
 topSpeed = 3 ;
 radius = mass*30 ;
} 

  void update(){
  velocity.add(acceleration);
  location.add(velocity); 
//  velocity.limit(topSpeed);   
  acceleration.mult(0);
  }

  void display(){
   fill(c);
   strokeWeight(mass);
  // ellipse(location.x,location.y,mass*40,mass*40);
      ellipse(location.x,location.y,radius,radius);
  }

  void applyForce(PVector force){
   PVector  f = PVector.div(force,mass);
   acceleration.add(f);
  }


    void checkEdges() {

    if (location.x > width-(radius/2)) {
      location.x = width-(radius/2);
      velocity.x *= -1;
    } else if (location.x < 0+(radius/2)) {
      velocity.x *= -1;
      location.x = 0+(radius/2);
    }
    if (location.y > height -(radius/2)) {
      velocity.y *= -1;
      location.y = height -(radius/2);
    }
  }

}

Tagged:

Answers

  • The problem is line 21 delete it - it is increasing the acceleration due to gravity for each sphere in turn.

    I deleted the line and it worked great with 100 spheres :D

  • yea I see ! but it doesnt make sense without that line . because the gravity force doesnt depend on Mass , and thats what Shiffman did in his Video .

    is there any other way to fix this bug ?!

  • edited October 2013 Answer ✓

    I think the situation here is that the program does not represent reality. ;))

    For visual effect the author has got the larger (therefore heavier) spheres falling more slowly than the lighter balls. Of course in reality you want them to fall at the same rate (i.e. acceleration due to gravity).

    The easiest solution is still to delete line 21 but change line 23 to

    s.applyForce(PVector.mult(gravity, s.mass)); 
    
  • yea ! that's a nice trick to make it work :D thanx man !

Sign In or Register to comment.