# Bouncing Throwable Ball

Hi all. I’ve made the basic bouncing ball, but I’m trying to make it so that it maintains the velocity of the cursor. is there something I did wrong?

``````PVector location;
PVector velocity;
PVector gravity;

int sz = 100;
color bgcolor;

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

void draw() {
background (#151515);
//so i can see what i'm doing
text("x: "+mouseX+" y: "+mouseY, 10, 15);

if (dist(location.x, location.y, mouseX, mouseY) < sz / 2) {
cursor(HAND);

if (mousePressed) {
location.x = mouseX;
location.y = mouseY;
strokeWeight(5);
} else {
strokeWeight(2);
}
stroke(255);
} else {
cursor(ARROW);
noStroke();
}

//bounce off edges
if ((location.x > width) || (location.x < 0)) {
velocity.x = velocity.x * -1;
}
if (location.y > height) {

//reduce the velocity when it hits the bottom of the window
velocity.y = velocity.y * -0.95;
location.y = height;
}

//the ball
stroke(255);
strokeWeight(2);
fill(127);
ellipse(location.x, location.y, 75, 75);

}
``````
1 Like

I can’t see where you do this.

Can you tell me the lines in your code you are referring to please?

And welcome to the forum, a great community.

Regards, Chrisir

1 Like

Hi! I’m happy to be here.

The problem is I can’t figure out how to do that. How would I go about this?

I understand that the faster you drag the mouse while holding the mouse button down (like drag and drop), the faster is the ball.

The way I see it you can measure the distance between the mouse and the previous mouse position

• to measure a distance use dist

• previous mouse position is pmouseX, pmouseY - see reference

• during the mouse dragging we search the biggest distance. That’s the velocity (or the 10 fold of it or so)

``````
boolean hold=false;
float biggest=-11111;

void setup() {
size(1000, 600);
background(200);
}

void draw() {
background(200);

if (hold) {
float newValue=dist(mouseX, mouseY, pmouseX, pmouseY);
println(newValue);
if (newValue>biggest) {
biggest=newValue;
}
}

fill(0);
text(biggest, 33, 33);
}

//------------------------------------------------------------------

void mousePressed() {
hold = true;
biggest=-11111;
}

void mouseReleased() {
hold = false;
}
``````
2 Likes