Okay, this is a fun one involving some physics and vector math!
Here's a p5.js program that simulates a ball bouncing inside a spinning hexagon.
Key Concepts Used:
-
Ball Physics:
- Position, Velocity, Acceleration.
- Gravity: A constant downward force.
- Air Drag (Friction): A slight damping applied to velocity each frame.
- Restitution (Bounciness/Friction on impact): How much energy is conserved during a bounce.
-
Hexagon:
- Defined by a center, radius, and current rotation angle.
- Vertices are calculated based on these parameters.
- Spins with a constant angular velocity.
-
Collision Detection:
- We check for collisions between the ball (a circle) and each of the 6 line segments forming the hexagon's edges.
- The core idea is to find the closest point on each edge segment to the ball's center.
- If the distance to this closest point is less than the ball's radius, a collision occurs.
-
Collision Response (Realistic Bouncing off Rotating Walls):
- Penetration Resolution: First, move the ball out of the wall so it's just touching. The collision normal points from the closest point on the wall to the ball's center.
- Wall Velocity: Calculate the velocity of the point of impact on the hexagon's edge due to its rotation. This is
v_wall = ω × r, where ω is the angular velocity and r is the vector from the hexagon's center to the impact point.
- Relative Velocity: Calculate the ball's velocity relative to the moving wall:
v_relative = ball.velocity - v_wall.
- Reflect Relative Velocity: Reflect the component of
v_relative that is normal to the wall. The amount of reflection is determined by the coefficient of restitution.
v_relative_normal_after = -restitution * v_relative_normal_before.
The change in velocity is -(1 + restitution) * v_relative_normal_before.
- Final Ball Velocity: The ball's new velocity is the reflected relative velocity plus the wall's velocity:
ball.velocity_new = v_relative_reflected + v_wall.
let ball;
let hexagon;
let gravity;
// --- Configuration ---
const HEX_RADIUS = 150;
const HEX_ANGULAR_VELOCITY = 0.005; // Radians per frame
const BALL_RADIUS = 15;
const BALL_RESTITUTION = 0.8; // Bounciness (0-1 range, 1 is perfectly elastic)
const GRAVITY_FORCE = 0.2;
const AIR_DRAG = 0.998; // Factor to multiply velocity by each frame
function setup() {
createCanvas(600, 600);
gravity = createVector(0, GRAVITY_FORCE);
hexagon = new Hexagon(width / 2, height / 2, HEX_RADIUS, HEX_ANGULAR_VELOCITY);
// Start ball slightly off-center to see interesting bounces
ball = new Ball(width / 2 + 20, height / 2 - 50, BALL_RADIUS, BALL_RESTITUTION);
}
function draw() {
background(220);
// Update and display hexagon
hexagon.update();
hexagon.display();
// Update and display ball
ball.applyForce(gravity);
ball.update();
handleCollisions(ball, hexagon);
ball.display();
// Instructions
fill(0);
noStroke();
textAlign(CENTER);
text("Ball bouncing in a spinning hexagon", width / 2, 20);
text(`Hexagon Angular Velocity: ${HEX_ANGULAR_VELOCITY.toFixed(3)} rad/frame`, width / 2, 40);
text(`Ball Restitution: ${BALL_RESTITUTION}`, width / 2, 60);
}
class Ball {
constructor(x, y, r, restitution) {
this.pos = createVector(x, y);
this.vel = createVector(random(-1,1), random(-1,1)); // Initial small random velocity
this.acc = createVector(0, 0);
this.radius = r;
this.restitution = restitution; // Coefficient of restitution
this.mass = this.radius * this.radius * PI; // Area as proxy for mass
}
applyForce(force) {
// F = ma, so a = F/m
let f = p5.Vector.div(force, this.mass * 0.01); // Scaled mass
this.acc.add(f);
}
update() {
this.vel.add(this.acc);
this.vel.mult(AIR_DRAG); // Apply air drag
this.pos.add(this.vel);
this.acc.mult(0); // Reset acceleration
}
display() {
fill(50, 100, 200);
noStroke();
ellipse(this.pos.x, this.pos.y, this.radius * 2);
}
}
class Hexagon {
constructor(x, y, r, angularVelocity) {
this.center = createVector(x, y);
this.radius = r;
this.angle = 0;
this.angularVelocity = angularVelocity;
this.vertices = [];
this.calculateVertices();
}
calculateVertices() {
this.vertices = [];
for (let i = 0; i < 6; i++) {
let a = this.angle + (TWO_PI / 6) * i;
let vx = this.center.x + this.radius * cos(a);
let vy = this.center.y + this.radius * sin(a);
this.vertices.push(createVector(vx, vy));
}
}
update() {
this.angle += this.angularVelocity;
this.calculateVertices(); // Recalculate vertices based on new angle
}
display() {
stroke(0);
strokeWeight(2);
fill(255, 200, 0, 150); // Semi-transparent yellow
beginShape();
for (let v of this.vertices) {
vertex(v.x, v.y);
}
endShape(CLOSE);
}
}
function handleCollisions(ball, hex) {
let vertices = hex.vertices;
for (let i = 0; i < vertices.length; i++) {
let v1 = vertices[i];
let v2 = vertices[(i + 1) % vertices.length]; // Next vertex, wraps around
// Find closest point on the line segment (edge) to the ball
let closestPoint = closestPointOnSegment(ball.pos, v1, v2);
let distToClosest = p5.Vector.dist(ball.pos, closestPoint);
if (distToClosest < ball.radius) {
// --- 1. Resolve Penetration ---
let penetrationDepth = ball.radius - distToClosest;
// Normal points from closest point on wall to ball's center
let collisionNormal = p5.Vector.sub(ball.pos, closestPoint).normalize();
ball.pos.add(p5.Vector.mult(collisionNormal, penetrationDepth));
// --- 2. Calculate Wall Velocity at Impact Point ---
// Vector from hexagon center to the impact point (closestPoint)
let r_contact = p5.Vector.sub(closestPoint, hex.center);
// v_wall = omega x r_contact (2D cross product: omega_z * r_contact_y, -omega_z * r_contact_x)
// but since our omega is positive for CCW, and coordinate system is y-down:
// v_wall.x = -angularVelocity * r_contact.y
// v_wall.y = angularVelocity * r_contact.x
let v_wall = createVector(
-hex.angularVelocity * r_contact.y,
hex.angularVelocity * r_contact.x
);
// --- 3. Calculate Relative Velocity ---
let v_relative = p5.Vector.sub(ball.vel, v_wall);
// --- 4. Reflect Relative Velocity ---
// Component of relative velocity along the normal
let vn_scalar = v_relative.dot(collisionNormal);
// Only bounce if ball is moving towards the wall along the normal
if (vn_scalar < 0) {
// Impulse magnitude for reflection (J = -(1+e) * m * vn)
// Assuming ball mass = 1 for simplicity in impulse calculation here,
// actual force application considers mass in ball.applyForce.
// For velocity change: delta_v_normal = -(1 + restitution) * vn_scalar
let impulseMagnitude = -(1 + ball.restitution) * vn_scalar;
let impulseVector = p5.Vector.mult(collisionNormal, impulseMagnitude);
// New relative velocity after bounce
let v_relative_after_bounce = p5.Vector.add(v_relative, impulseVector);
// --- 5. Final Ball Velocity ---
ball.vel = p5.Vector.add(v_relative_after_bounce, v_wall);
}
}
}
}
// Helper function to find the closest point on a line segment (a-b) to point p
function closestPointOnSegment(p, a, b) {
let ap = p5.Vector.sub(p, a);
let ab = p5.Vector.sub(b, a);
let abMagSq = ab.magSq();
if (abMagSq === 0) return a.copy(); // a and b are the same point
let t = ap.dot(ab) / abMagSq;
t = constrain(t, 0, 1); // Clamp t to be between 0 and 1
return p5.Vector.add(a, p5.Vector.mult(ab, t));
}
How to Run:
- Go to the p5.js online editor: editor.p5js.org
- Copy and paste the entire code into the editor.
- Press the "Play" button.
Explanation of Tricky Parts:
closestPointOnSegment(p, a, b): This function is crucial. It projects the vector from one segment endpoint a to the point p (ap) onto the segment vector ab. The scalar projection t tells us where the closest point lies. If t < 0, the closest point is a. If t > 1, it's b. Otherwise, it's along the segment.
- Rotating Frame Collision:
- The
v_wall calculation is based on v = ω × r. For 2D, if ω is along the z-axis (out of the screen), and r = (rx, ry), then v = (-ω * ry, ω * rx). This gives the velocity of the hexagon's edge at the point of impact.
- We then transform the ball's velocity into the frame of reference of the moving wall (
v_relative).
- The bounce physics (reflection) is applied to this
v_relative.
- Finally, we transform the new relative velocity back into the world frame by adding
v_wall.
- Restitution (
ball.restitution): This controls how "bouncy" the collision is. A value of 1 would be perfectly elastic (no energy loss in the normal direction of the bounce). A value of 0 would mean the ball loses all its normal velocity component relative to the wall.
- Air Drag (
AIR_DRAG): A simple way to simulate friction with the air, causing the ball to gradually slow down if no other forces act on it or after bounces.
- Gravity (
GRAVITY_FORCE): Applied as a constant downward acceleration. The ball.applyForce method divides by mass, so larger (heavier) balls would be less affected by the same gravity force, but here gravity is more like a direct acceleration value. I scaled mass slightly in applyForce to make it more apparent.
This program provides a good approximation of realistic bouncing physics. For even more accuracy, one might consider tangential friction (affecting spin) and more complex collision shapes, but this version should be visually convincing!