Drawing Line with Bouncing Ball

Hello! I am a beginner, and I’m very new to processing!

I have a project in mind that I have no idea how to execute. I want to create something from the bouncing ball example. Supposedly, the code will draw a line from the center of the ball to track where the ball has been.

So far, I created a dot in the middle of the circle.

PVector location;  // Location of shape
PVector velocity;  // Velocity of shape
PVector gravity;   // Gravity acts at the shape's acceleration

void setup() {
  size(640,360);
  location = new PVector(100,100);
  velocity = new PVector(1.5,2.1);
  gravity = new PVector(0,0.2);
}

void draw() {
  background(0);
  
  location.add(velocity);
  // Add gravity to velocity
  velocity.add(gravity);
  
  // Bounce off edges
  if ((location.x > width) || (location.x < 0)) {
    velocity.x = velocity.x * -1;
  }
  if (location.y > height) {
    velocity.y = velocity.y * -1; 
    location.y = height;
  }

  stroke(255);
  strokeWeight(2);
  fill(127);
  ellipse(location.x,location.y, 48, 48);
  line(location.x, location.y, location.x, location.y);
  }

This creates a dot, but leaves no trail. I assume it’s because I have no idea how to obtain the location of the center of the ball of the previous frame.

Thank you for reading!

Hello @SodaPopPop
If I’m reading your question correctly, I think you will need to use the point() function rather than line() function. And create an arrayList in order to store the locations of all of the previous points as well as each new point (x, y location) as long as the sketch runs.
I hope this helps.
:nerd_face:

1 Like

Thank you! I’ll test it and update here about whether that works.

1 Like

For a start just comment this out

1 Like

Oh! I did as soon as I realized it’s drawing the background every frame. Though, it will draw the circle every frame too. I’ll try it out first. Thanks!

1 Like

The idea from debxyz is very good

You need an Arraylist of PVector, add() points to it and display the whole list in draw()

Then you can re-activate background() actually

Details

before setup():

ArrayList<PVector> list = new ArrayList();

in draw() add the points:

list.add(new PVector(x,y)); // or what the position of the ball is named in your Sketch

and display the points

for(PVector currentPV : list) {
    point(currentPV.x,currentPV.y); 
}

Chrisir

2 Likes

Hi,

This thread could help: Smart-ish bouncing ball

2 Likes

Thank you! This helped immensely!

1 Like

Thank you for the link! It does help with deepening my understanding of the language.