Charge a throw
Updated
Hold Space to charge and release to throw a ball: the keyboard state sets the strength of an impulse on its Rigid Body.
Click the scene, then hold Space and release it to throw the ball. Drag to orbit the camera, scroll to zoom.
Charge a throw
#pragma lifecycle(startup, update)
const MAX_CHARGE = 1.5; // seconds to full powerconst MAX_IMPULSE = 12;let charge = 0;let ball;
function startup() { ball = findEntity('Ball').getComponent(PhysicsRigidBodyComponent);}
function update(dt) { const keys = Input.keyboard;
// Hold Space to charge, release to throw. if (keys.isKeyPressed(Key.Space)) charge = Math.min(MAX_CHARGE, charge + dt); if (keys.isKeyReleased(Key.Space)) { const power = (charge / MAX_CHARGE) * MAX_IMPULSE; ball.applyImpulse({ x: 0, y: power * 0.5, z: -power }); log(`Thrown at ${Math.round((charge / MAX_CHARGE) * 100)}% power`); charge = 0; }
// Hold F to fire four times a second. if (keys.isKeyPressedFor(Key.F, 0.25)) emit('player/fire');}How it works
Section titled “How it works”The script is explained step by step in Charge a throw.
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.
ChargeAndThrow.xrproj