collision and gravity balls

edited August 2015 in Questions about Code

hey! im new to processing and i have a question.... how can i make a ball bounce when collides with a line? not losing the gravity factor of course.. thanks in advance!

the code is here:

Tagged:

Answers

  • You'll get a better response if you format your code. Here's how:

    http://forum.processing.org/two/discussion/8045/how-to-format-code-and-text

  • Also we don't have your Ball class. That's sort of important for us to have is we're going to try running this to see what your problem is.

  • edited August 2015

    thank you guys ok so this is the main:

    import java.util.Vector;
    
    Ball[] bolas;
    float ball_gravity = 0.5;
    
    void setup() {
      size(400,400);
      smooth();
      noCursor();
      stroke(1);
      fill(255);
      line(width/2, height/2, width/2+50, height/2+50);  
      bolas = new Ball[1];
     bolas[0]=new Ball(50,0,30);
    
    }
    
    void draw() {
      background(255);
       stroke(1);
      fill(255);
      line(width/2, height/2, width/2+100, height/2+100);  
    
      rectMode(CENTER);
      stroke(0);
      fill(color(#B40D56));
      rect(mouseX,mouseY,4,30);
      for (int i = 0; i < bolas.length; i ++ ) { // Whatever the length of that array, update and display all of the objects.
        bolas[i].gravity(ball_gravity);
        bolas[i].move();
        bolas[i].rollOver(mouseX,mouseY,pmouseX);
        bolas[i].display();
      }
    }
    
    void mousePressed() {
      // A new ball object
      Ball b = new Ball(mouseX,mouseY,30); // Make a new object at the mouse location.
      bolas =  (Ball[]) append(bolas,b);
    
    }    
    

    and this is the class ball

    class Ball {
      float x;
      float y;
      float speed;
      float w;
      color cor;
    
      Ball(float tempX, float tempY, float tempW) {
        x = tempX;
        y = tempY;
        w = tempW;
        speed = 0;
        cor=color(int(random(250)),int(random(250)),int(random(250)));
      }
    
      void gravity(float gravity) {
        // Add gravity to speed
        speed = speed + gravity;
      }
    
      void move() {
        // Add speed to y location
        y = y + speed;
        // If square reaches the bottom
        // Reverse speed
        if (y > height) {
          speed = speed * -0.90;
          y = height;
        }
      }
    
      void rollOver(int mx, int my, int pmx){
        float d=dist(mx,my,x,y);
        if(d<=w/2){
          if(pmx>mx)
            x=x-30;
          else
            x=x+30;
          x=constrain(x,0,width);
        }
      }
    
      void display() {
        // Display the circle
        ellipseMode(CENTER);
        fill(cor);
        stroke(0);
        ellipse(x,y,w,w);
      }
    } 
    
  • code: 2 empty lines before and after

    select entire code with mouse

    hit ctrl-o

    OR the small C in the small command bar

Sign In or Register to comment.