Kick a ball where it was clicked
Updated
A click on the ball casts a physics ray and applies an impulse along it at the point hit, so an off-centre click also sets the ball spinning.
Click the ball to kick it away from you; click its edge to make it spin. Drag to orbit the camera, scroll to zoom.
Kick a ball where it was clicked
#pragma lifecycle(startup, update)
const STRENGTH = 4;const push = new THREE.Vector3();
let ball;let body;
function startup() { ball = findEntity('Ball'); body = ball.getComponent(PhysicsRigidBodyComponent);}
function update() { if (!Input.mouse.isButtonReleased(MouseButton.Left)) return; const ray = PhysicsRaycaster.fromScreen(Input.mouse.position()); const hit = ray.hit(ball); if (!hit) return;
push.copy(ray.ray.direction).multiplyScalar(STRENGTH); body.applyImpulseAtPoint(push, hit.point);}How it works
Section titled “How it works”The script is explained step by step in Kick a ball where it was clicked.
Open it in XR Creator
Section titled “Open it in XR Creator”Download the project file below, then import it in XR Hub with Projects › New › Import, as described in Projects and templates. It opens in XR Creator with the same scene you see running above, each script already attached to its Behavior entity. From there you can edit the scripts, adjust components and their props, preview your changes, and deploy the result as a world of your own.
KickBall.xrproj