This simulation demonstrates the physics behind the Ball Acceleration towards the target - in this scenario, the mouse pointer.
Acceleration is the rate of change of velocity of an object. Unlike the bouncing ball, which moves at a constant speed or velocity, this ball gradually increases its speed towards the mouse position. The closer it gets, the smaller the acceleration becomes.
let x = 100, y = 100;
let vx = 0, vy = 0;
let ax = 0, ay = 0;
const a_rate = 0.1; // Acceleration rate
const maxSpeed = 5; // Maximum speed
function draw(mouseX, mouseY){
// Calculate direction to mouse
let dirX = mouseX - x;
let dirY = mouseY - y;
let length = Math.sqrt(dirX * dirX + dirY * dirY);
// Normalize direction and apply acceleration
ax = (dirX / length) * a_rate;
ay = (dirY / length) * a_rate;
vx += ax;
vy += ay;
// Limit speed to maxSpeed (limiting velocity to max speed)
let speed = Math.sqrt(vx * vx + vy * vy);
if(speed > maxSpeed) {
vx = (vx / speed) * maxSpeed;
vy = (vy / speed) * maxSpeed;
}
// Update position
x += vx;
y += vy;
}| Parameter | Description | Example Value |
|---|---|---|
| Ball Size | Determines the visual size of moving ball. | 48 |
| Max Speed | Sets the highest velocity the ball can reach. | 5 |
| Acceleration Rate | Controls how quickly the ball accelerates towards the mouse. | 0.1 |