Fire from the muzzle
Updated
Each click spawns a bullet at the gun’s muzzle and pushes it along the barrel: CoordinateSpace.localToWorld turns points in the gun’s own space into world points.
Click anywhere in the view to fire. Drag to orbit the camera, scroll to zoom.
Fire from the muzzle
#pragma lifecycle(startup, update)
const MUZZLE = { x: 0, y: 0.05, z: -0.4 }; // the barrel's tip, in the gun's own spaceconst AHEAD = { x: 0, y: 0.05, z: -1.4 }; // one metre further along the barrellet gun;
function startup() { gun = findEntity('Gun');}
function update() { if (!Input.mouse.isButtonReleased(MouseButton.Left)) return;
const tip = CoordinateSpace.localToWorld(MUZZLE, gun); const ahead = CoordinateSpace.localToWorld(AHEAD, gun); const direction = ahead.clone().sub(tip).normalize();
const bullet = spawn('Bullet', { position: tip, enabled: true }); bullet.getComponent(PhysicsRigidBodyComponent)?.applyImpulse(direction.multiplyScalar(5));}How it works
Section titled “How it works”The script is explained step by step in Fire from the muzzle.
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.
MuzzleFire.xrproj