Hi,
Welcome to the forum!
If you want to move the balls away from the mouse, think of it as a magnet. A magnet is applying a magnetic field on a piece of metal that may repulse it :
Since we are doing some geometry here, you need to think with vectors. If you don’t really know how they work, you can check this tutorial on the Processing website :
https://processing.org/tutorials/pvector/
The idea is to apply a force on the Ball that is in the opposite direction compared to the mouse cursor. This force depends on the distance d
from the ball to the mouse since we want them to be more pushed away as soon as they are close to the mouse
A force can be represented as a vector, here represented at the origin of the ball.
In Processing, you would do :
// A position is also a vector
PVector mouseLocation = new PVector(mouseX, mouseY);
// The force is the difference between the two locations
PVector repulsionForce = PVector.sub(ballLocation, mouseLocation);
// Compute the distance between the ball and the cursor
// This is the length of the vector
float distanceFromMouse = repulsionForce.mag();
// If it's close enough to the mouse
if (distanceFromMouse < 100) {
// We then normalize the vector so it's length is 1
repulsionForce.normalize();
// We multiply it by a certain amount (the power of the repulsion) that depends on the distance from the mouse
repulsionForce.mult(map(distanceFromMouse, 0, 100, 2, 0));
// We add the force to the velocity of the ball
ballVelocity.add(repulsionForce);
}
// Update the ball location
ballLocation.add(velocity);
If you don’t know what some functions do, check the documentation :
So this is the basic idea, it will be in an update method for each ball so they have their own location and velocity as a vector rather than separate variables for xSpeed
and ySpeed
.
This may be confusing at first but vectors gives you some nice features : you can add other points that repulse the balls, others that attract them, add acceleration to the balls, collisions…
Hope it helps!