Picking and raycasts
Updated
A raycast sends an invisible line, a ray, into the scene and reports what it meets. It is how a script answers the questions it asks most often about space: what is under the mouse or the finger, what an XR controller points at, whether a wall stands between a guard and the player, where a shot lands, or where the real floor is in augmented reality. MIRA has three raycasters, each testing against something different, and they all return their results in the same simple shape.
Before you start
Section titled “Before you start”You should know:
- How to read the mouse, touches and XR controllers; see Keyboard, mouse and touch and XR controllers and hands.
- What screen points are: CSS pixels from the top-left of the page; see Key concepts.
- For
PhysicsRaycaster, what colliders and physics layers are; see Physics and Physics layers.
Three raycasters
Section titled “Three raycasters”| Global | Tests against | Use it for |
|---|---|---|
Graphics |
What is drawn: meshes, lines, points and sprites, down to the triangle. | Clicking and pointing at anything visible. |
Physics |
Colliders in the physics world: one query over a few simple shapes. | Shots, lines of sight and ground checks. Much faster on objects with colliders, and exactly what physics blocks. |
XRRaycaster |
The real world, asked of the device during an immersive session. | Placing content on real floors, walls and tables in AR. |
You never create a raycaster with new: each one has factory functions that build a ray for you.
Making a ray
Section titled “Making a ray”GraphicsRaycaster and PhysicsRaycaster share four factories:
| Factory | The ray |
|---|---|
from |
From the camera through a screen point: what Input. and Input. give. |
from |
From point towards direction, in the world. Without a direction, from the camera through point. |
from |
Along where an XR controller or hand points. null while it is not connected or not tracked. |
between(a, b) |
From a to b, going no farther than b: is anything in the way? |
cameradefaults to the camera the player sees through.- Points and directions accept a
THREE.Vector3or any{ x, y, z }object.
Asking the ray
Section titled “Asking the ray”| Call | What it returns |
|---|---|
hit(targets?, options?) |
The nearest hit, or null. |
hits(targets?, options?) |
Every hit, nearest first. |
ground(height = 0) |
Where the ray meets a level plane at height, as a new vector; null when it points away from it, such as into the sky. |
The arguments:
targetslimits the test to one object or a list of objects, with everything under them.nullor absent tests the whole scene.options.maxDistanceignores hits farther away.options.ignoreis an object or a list of objects the ray passes through, with everything under them. Usually the caster itself,self.options.collisionLayers(PhysicsRaycasteronly) is a list of physics layer ids from0to15: the ray hits only colliders on those layers. Absent means every layer; an empty list means none.
| Field | What it is |
|---|---|
entity |
The entity hit: the nearest entity above the mesh that was hit. null for a mesh that belongs to no entity. |
object |
The exact object hit, often a mesh inside the entity. For a collider, the entity itself. |
point |
Where, in world space. |
normal |
The direction the surface faces at that point, in world space. null for lines and points, and for a ray that starts inside a collider. |
distance |
How far from the ray’s start. |
Every vector in a hit is a new copy, so you can keep or change it.
Graphics or physics
Section titled “Graphics or physics”Both raycasters answer the same questions, but they see the scene differently.
GraphicsRaycaster tests what is drawn:
- It skips hidden objects and the local player’s own first-person body.
- It is exact to the triangle, so it works on any model, with or without colliders.
PhysicsRaycaster tests colliders:
hit.objectis the entity that owns the collider, likehit.entity. A body with several colliders can be hit once per collider.- Sensors (trigger colliders) are never hit. A hidden entity’s collider still is, so an invisible wall blocks a shot.
- A ray that starts inside a collider hits it at distance
0with anullnormal. Passignore: selfwhen casting from inside the caster. - It works in play only. In the editor, and while physics is still loading, nothing is hit. A collider created this frame is hit from the next physics step.
- A moving rigid body is drawn smoothly between physics steps, so what you see can be up to one step (1/60 s) behind the body the ray tests.
XRRaycaster
Section titled “XRRaycaster”XRRaycaster asks the device instead of the scene. During an immersive AR session, the device understands the real room, and the ray is a hit test against its real floor, walls, tables and whatever else it recognises.
| Factory | The ray |
|---|---|
XRRaycaster. |
Along a controller or hand ray; null while it is not there. |
XRRaycaster. |
Straight ahead of the headset, or of the phone’s camera: ideal for a reticle. |
XRRaycaster. |
Through the finger touching an AR phone’s screen; hits nothing while no finger touches. |
hit({ maxDistance? }) returns the nearest real-world hit or null; hits({ maxDistance? }) returns every one, nearest first.
| Real-world hit field | What it is |
|---|---|
point |
Where, in world space. |
normal |
The real surface’s facing there. |
orientation |
A rotation standing on the surface, its up along normal: copy it to place something there. |
distance |
How far from the controller, or from the head for the viewer and screen rays. |
result |
The device’s own result, which XRAnchor anchors on. |
- The device answers once per frame, and a ray’s first question starts the answering: results arrive in the following frames. Ask every frame, as a reticle does.
- Nothing is hit outside a session, in the editor, or where the device cannot hit-test.
- To cast any other kind of ray against the room, use
PhysicsRaycasterorGraphicsRaycasteragainst the surfaces that XR Planes and XR Meshes bring into the scene; see XR world.
Examples
Section titled “Examples”1. Click to pick and show where
Section titled “1. Click to pick and show where”#pragma lifecycle(startup, update)
let marker;
function startup() { marker = findEntity('Hit Marker'); marker.visible = false;}
function update() { if (!Input.mouse.isButtonReleased(MouseButton.Left)) return;
const hit = GraphicsRaycaster.fromScreen(Input.mouse.position()).hit(null, { ignore: marker }); marker.visible = Boolean(hit); if (!hit) return;
marker.position.copy(hit.point); if (hit.normal) marker.lookAt(hit.point.clone().add(hit.normal)); if (hit.entity) log(`Clicked ${hit.entity.name}, ${hit.distance.toFixed(2)} m away`);}Each click casts a GraphicsRaycaster ray from the mouse, ignores the marker itself, and moves the marker to the hit point.
Click the shapes or the floor. Drag to orbit the camera, scroll to zoom.
fromScreenbuilds a ray from the camera through the mouse position.hit(null, { ignore: marker })tests the whole scene but passes through the marker itself, so it never picks its own indicator.- The marker moves to
hit.point.lookAttowards a point one unit alonghit.normalturns it to face out of the surface, like a decal. hit.entitycan benullfor a mesh outside any entity, so it is checked before reading its name.
2. Line of sight between a guard and the player
Section titled “2. Line of sight between a guard and the player”#pragma lifecycle(startup, update)
const SIGHT = 12; // metresconst guardEye = new THREE.Vector3();const playerEye = new THREE.Vector3();let guard;let player;let alerted = false;
function startup() { guard = findEntity('Guard'); player = findEntity('Player');}
function update() { guard.getWorldPosition(guardEye).y += 1.6; player.getWorldPosition(playerEye).y += 1.6;
const close = guardEye.distanceTo(playerEye) < SIGHT; const blocked = close && PhysicsRaycaster.between(guardEye, playerEye).hit(null, { ignore: [guard, player] }); const sees = close && !blocked;
if (sees !== alerted) { alerted = sees; emit(sees ? 'guard/alert' : 'guard/calm'); }}Every frame a physics ray runs from the guard’s eyes to the player’s; when nothing blocks it the guard is alerted, and an Enable On Signal shows the alarm above its head.
Drag the blue player out from behind the wall: the pink alarm lights while the guard can see it. Drag elsewhere to orbit the camera, scroll to zoom.
- Both positions are raised to eye height so a knee-high crate does not block the view.
- The ray is only cast when the player is within range: a cheap distance check first saves work.
betweencasts from the guard’s eyes to the player’s and stops there, so walls behind the player do not count.ignorepasses through both characters’ own colliders.alertedremembers the last state, so each signal is emitted once per change.
3. Tap the ground to place an object
Section titled “3. Tap the ground to place an object”#pragma lifecycle(startup, update)
let flag;let terrain;
function startup() { flag = findEntity('Flag'); terrain = findEntity('Terrain');}
function update() { const tap = Input.touch.touch(0); const clicked = Input.mouse.isButtonReleased(MouseButton.Left); const point = tap && tap.phase === 'end' ? tap : clicked ? Input.mouse.position() : null; if (!point) return;
const ray = GraphicsRaycaster.fromScreen(point); const surface = ray.hit(terrain); const spot = surface ? surface.point : ray.ground(); if (spot) flag.setPosition(spot.x, spot.y, spot.z);}A click or a tap casts a ray from the camera: the flag is placed where it meets the hill, or on the level ground when it misses the hill.
Click or tap the hill or the floor to plant the flag there. Drag to orbit the camera, scroll to zoom.
- A finished tap or a mouse click gives the screen point; a touch can be passed to
fromScreendirectly. hit(terrain)limits the test to the terrain and its children, so the flag lands on the ground even if a tree is in the way. The terrain is looked up once, instartup.- If the terrain is missed,
ground()falls back to the level plane at height 0. It returnsnullwhen the ray points at the sky. setPositionmoves the flag, and its physics body if it has one.
Snippets
Section titled “Snippets”1. Hover detection on chosen physics layers
Section titled “1. Hover detection on chosen physics layers”#pragma lifecycle(update)
const PICKABLE = [1, 2]; // physics layers of the interactive propslet hovered = null;
function update() { const hit = PhysicsRaycaster.fromScreen(Input.mouse.position()).hit(null, { collisionLayers: PICKABLE }); const now = hit ? hit.entity : null; if (now === hovered) return;
if (hovered) emit('hover/leave', { id: hovered.entityId }); if (now) emit('hover/enter', { id: now.entityId }); hovered = now;}- The ray runs every frame, so
PhysicsRaycasterkeeps it cheap.PICKABLEis a constant, so no array is created each frame. collisionLayersrestricts the test to layers 1 and 2: floors, walls and scenery on other layers are ignored.- The script compares this frame’s entity with last frame’s and emits only when the hover changes.
2. Shoot forward, ignoring yourself
Section titled “2. Shoot forward, ignoring yourself”#pragma lifecycle(update)
const RANGE = 50;const forward = new THREE.Vector3();const origin = new THREE.Vector3();
function update() { if (!Input.keyboard.isKeyReleased(Key.Space)) return;
self.getWorldPosition(origin); self.getWorldDirection(forward); forward.negate(); // getWorldDirection gives +Z; entities face -Z
const shot = PhysicsRaycaster.fromWorld(origin, forward).hit(null, { maxDistance: RANGE, ignore: self }); if (!shot) return log('Missed');
log(`Hit ${shot.entity.name} at ${shot.distance.toFixed(1)} m`); emit('damage', { id: shot.entity.entityId, amount: 10, at: shot.point });}- Two scratch vectors are created once and reused every frame, which avoids creating garbage.
getWorldDirectiongives the entity’s +Z axis in world space; negating it gives the forward direction, -Z.fromWorld(origin, forward)casts from the entity along its facing.maxDistancelimits the range, andignore: selfstops the shooter from hitting its own collider.
3. A laser pointer for an XR controller
Section titled “3. A laser pointer for an XR controller”#pragma lifecycle(startup, update)
let right;let dot;
function startup() { right = Input.xr.controller('right'); dot = findEntity('Laser Dot');}
function update() { const ray = GraphicsRaycaster.fromController(right); const hit = ray && ray.hit(null, { maxDistance: 10, ignore: dot }); dot.visible = Boolean(hit); if (!hit) return;
dot.position.copy(hit.point); if (right.isReleased(XRButton.Trigger) && hit.entity) emit('xr/select', { id: hit.entity.entityId });}fromControllerreturnsnullwhile the controller is not tracked, which also hides the dot.- The dot is ignored by the ray, so it never blocks its own pointer.
- The trigger selects whatever the dot is on.
4. An AR reticle
Section titled “4. An AR reticle”#pragma lifecycle(startup, update)
let reticle;
function startup() { reticle = findEntity('Reticle'); reticle.visible = false;}
function update() { const hit = XRRaycaster.fromViewer().hit(); reticle.visible = Boolean(hit); if (!hit) return;
reticle.position.copy(hit.point); reticle.quaternion.copy(hit.orientation); if (Input.xr.controller(0).isReleased(XRButton.Trigger)) emit('ar/place', { point: hit.point });}fromViewercasts straight ahead of the head or the phone camera, and is asked every frame, as the device answers a frame later.orientationlays the reticle flat on the real surface, whether floor, table or wall.- On a phone, a screen tap is XR input 0 and reads as the trigger. To pin content to that spot, see XR anchors.
Common mistakes
Section titled “Common mistakes”- Hitting the caster itself. A ray cast from inside an entity’s collider hits it at distance
0. Passignore: self. - Expecting
PhysicsRaycasterto see triggers. Sensors are never hit. Use collision events for trigger volumes; see Collisions and triggers. - Using
PhysicsRaycasterin the editor. Physics does not step in the editor, so it hits nothing there. UseGraphicsRaycasterin editor scripts. - Reading
hit.entitywithout a check.hitisnullon a miss, andhit.entitycan benullfor a mesh outside any entity. - Building lists every frame. Keep
collisionLayersandignorelists in constants or variables set up instartup. - Asking
XRRaycasteronce. The device answers a frame later. Ask every frame while you need a result.