3D Physics Ball
https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js
// Scene setup
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Ball
const geometry = new THREE.SphereGeometry(0.5, 32, 32);
const material = new THREE.MeshStandardMaterial({ color: 0xff0055 });
const ball = new THREE.Mesh(geometry, material);
scene.add(ball);
// Plane
const planeGeometry = new THREE.PlaneGeometry(10, 10);
const planeMaterial = new THREE.MeshStandardMaterial({ color: 0xcccccc, side: THREE.DoubleSide });
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.rotation.x = Math.PI / 2;
scene.add(plane);
// Light
const light = new THREE.PointLight(0xffffff, 1, 100);
light.position.set(5, 5, 5);
scene.add(light);
const ambientLight = new THREE.AmbientLight(0x404040); // Soft ambient light
scene.add(ambientLight);
// Physics variables
let velocity = 0.05; // Ball velocity
let gravity = -0.005; // Gravity force
let bounceFactor = 0.8; // Energy loss on bounce
// Animation loop
function animate() {
requestAnimationFrame(animate);
// Update ball position and velocity
ball.position.y += velocity;
velocity += gravity;
// Bounce off the plane
if (ball.position.y – 0.5 {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
animate();