Skip to content

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.

You should know:

Global Tests against Use it for
GraphicsRaycaster What is drawn: meshes, lines, points and sprites, down to the triangle. Clicking and pointing at anything visible.
PhysicsRaycaster 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.

GraphicsRaycaster and PhysicsRaycaster share four factories:

Factory The ray
fromScreen(point, camera?) From the camera through a screen point: what Input.mouse.position() and Input.touch.touch(i) give.
fromWorld(point, direction?, camera?) From point towards direction, in the world. Without a direction, from the camera through point.
fromController(controller) 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?
  • camera defaults to the camera the player sees through.
  • Points and directions accept a THREE.Vector3 or any { x, y, z } object.
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:

  • targets limits the test to one object or a list of objects, with everything under them. null or absent tests the whole scene.
  • options.maxDistance ignores hits farther away.
  • options.ignore is an object or a list of objects the ray passes through, with everything under them. Usually the caster itself, self.
  • options.collisionLayers (PhysicsRaycaster only) is a list of physics layer ids from 0 to 15: 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.

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.object is the entity that owns the collider, like hit.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 0 with a null normal. Pass ignore: self when 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 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.fromController(controller) Along a controller or hand ray; null while it is not there.
XRRaycaster.fromViewer() Straight ahead of the headset, or of the phone’s camera: ideal for a reticle.
XRRaycaster.fromScreen() 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 XRAnchorComponent.anchorAt(hit) 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 PhysicsRaycaster or GraphicsRaycaster against the surfaces that XR Planes and XR Meshes bring into the scene; see XR world.
PickWithMarker.jx
#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`);
}
  • fromScreen builds 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. lookAt towards a point one unit along hit.normal turns it to face out of the surface, like a decal.
  • hit.entity can be null for 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”
GuardSight.jx
#pragma lifecycle(startup, update)
const SIGHT = 12; // metres
const 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');
}
}
  • 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.
  • between casts from the guard’s eyes to the player’s and stops there, so walls behind the player do not count. ignore passes through both characters’ own colliders.
  • alerted remembers the last state, so each signal is emitted once per change.
TapToPlace.jx
#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 finished tap or a mouse click gives the screen point; a touch can be passed to fromScreen directly.
  • 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, in startup.
  • If the terrain is missed, ground() falls back to the level plane at height 0. It returns null when the ray points at the sky.
  • setPosition moves the flag, and its physics body if it has one.

1. Hover detection on chosen physics layers

Section titled “1. Hover detection on chosen physics layers”
HoverLayers.jx
#pragma lifecycle(update)
const PICKABLE = [1, 2]; // physics layers of the interactive props
let 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 PhysicsRaycaster keeps it cheap. PICKABLE is a constant, so no array is created each frame.
  • collisionLayers restricts 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.
Hitscan.jx
#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.
  • getWorldDirection gives 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. maxDistance limits the range, and ignore: self stops the shooter from hitting its own collider.
LaserDot.jx
#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 });
}
  • fromController returns null while 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.
ARReticle.jx
#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 });
}
  • fromViewer casts straight ahead of the head or the phone camera, and is asked every frame, as the device answers a frame later.
  • orientation lays 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.
  • Hitting the caster itself. A ray cast from inside an entity’s collider hits it at distance 0. Pass ignore: self.
  • Expecting PhysicsRaycaster to see triggers. Sensors are never hit. Use collision events for trigger volumes; see Collisions and triggers.
  • Using PhysicsRaycaster in the editor. Physics does not step in the editor, so it hits nothing there. Use GraphicsRaycaster in editor scripts.
  • Reading hit.entity without a check. hit is null on a miss, and hit.entity can be null for a mesh outside any entity.
  • Building lists every frame. Keep collisionLayers and ignore lists in constants or variables set up in startup.
  • Asking XRRaycaster once. The device answers a frame later. Ask every frame while you need a result.