# Locomotion

In XR, users walk around their room, and the headset moves the camera with them. To take them further than their room allows, move the camera's parent, the [rig](https://developer.playcanvas.com/user-manual/xr/sessions.md#the-camera-and-its-rig). The headset moves the camera within the rig, and the rig carries the camera, the controllers and the hands through the scene.

This page covers moving the rig yourself, and the engine's `XrNavigation` script, which lets users teleport, move and turn with their controllers and hands.

[Video](https://developer.playcanvas.com/video/xr-locomotion.mp4)

## Moving the Rig

Move the rig to move the user, and rotate it about the vertical axis to turn them. The user's head is rarely above the rig's origin, as they move around their room, so:

- **To teleport the user to a point**, move the rig so that their head, rather than the rig's origin, ends up above the point.
- **To turn the user**, rotate the rig about their head, rather than about its origin, so that they turn on the spot.

```javascript
// Move the user so that their head is above a point on the floor
const teleportTo = (point) => {
    const head = camera.getPosition();
    const origin = rig.getPosition();
    rig.setPosition(point.x - (head.x - origin.x), point.y, point.z - (head.z - origin.z));
};

// Turn the user about their head, by an angle in degrees
const headBefore = new Vec3();
const turn = (degrees) => {
    headBefore.copy(camera.getPosition());
    rig.rotate(0, degrees, 0);
    rig.translate(headBefore.sub(camera.getPosition()));
};
```

These assume a `local-floor` [reference space](https://developer.playcanvas.com/user-manual/xr/sessions.md#reference-spaces), in which the rig's origin is on the floor, and a rig with no parent and no scale.

To put the user somewhere when a session starts, place the camera there before it starts. The [`XrSession`](https://developer.playcanvas.com/user-manual/xr/sessions.md#with-the-xrsession-script) script moves the rig to the ground below the camera, facing the same way.

## The XrNavigation Script

The `XrNavigation` script offers several ways to move at once, so that users can choose the ones they're comfortable with:

| Input | What it does |
| --- | --- |
| Hold select (the trigger, or a pinch), aim, and let go | Teleports. While the user aims, an arc shows where they would land, in red where they can't |
| Left thumbstick | Moves smoothly, relative to the way the user faces |
| Right thumbstick, left or right | Turns, by 45° each time the user pushes it, or smoothly |
| Right thumbstick, forward or back | Rises or sinks 0.5 meters each time the user pushes it, or 2 meters while they hold the right grip |

Hands have no thumbsticks, so with hands, users teleport by pinching. The script ignores the pinches that open the system menu on a Meta Quest.

Add the script to the rig, before the session starts:

**Engine**

```javascript
import { XrNavigation } from 'playcanvas/scripts/esm/xr/xr-navigation.mjs';

rig.script.create(XrNavigation, {
    properties: {
        turnMode: 'smooth',
        enableSnapVertical: false
    }
});
```

**Editor**

1. Add `xr-navigation.mjs`, from the `scripts/esm/xr` folder of the [engine repository](https://github.com/playcanvas/engine/tree/main/scripts/esm/xr), to your project as a script asset.
2. Select the rig, and add **xrNavigation** to its Script component.
3. Set the script's attributes in the Inspector.

**React**

```jsx
import { Entity } from '@playcanvas/react';
import { Script } from '@playcanvas/react/components';
import { XrNavigation } from 'playcanvas/scripts/esm/xr/xr-navigation.mjs';

export function Rig({ children }) {
  return (
    <Entity name="rig">
      {children}
      <Script script={XrNavigation} turnMode="smooth" enableSnapVertical={false} />
    </Entity>
  );
}
```

**Web Components**

Declare the script in a `<pc-asset>` inside `<pc-app>`:

```html
<pc-asset src="https://cdn.jsdelivr.net/npm/playcanvas@latest/scripts/esm/xr/xr-navigation.mjs"></pc-asset>

<pc-entity name="rig">
    <!-- the camera ... -->
    <pc-script>
        <pc-script-instance name="xrNavigation" turn-mode="smooth" enable-snap-vertical="false"></pc-script-instance>
    </pc-script>
</pc-entity>
```

The camera must be a child of the rig, as the script moves the user relative to the camera. Its main attributes:

| Attribute | Default | Description |
| --- | --- | --- |
| `enableTeleport` | `true` | Teleport with select |
| `enableMove` | `true` | Move with the left thumbstick, and turn with the right one |
| `movementSpeed` | 1.5 | The speed of thumbstick movement, in meters per second |
| `turnMode` | `'snap'` | `'snap'` to turn in steps, `'smooth'` to turn while the thumbstick is held, or `'none'` |
| `rotateSpeed` | 45 | The angle of each snap turn, in degrees |
| `smoothTurnSpeed` | 90 | The speed of smooth turning, in degrees per second |
| `enableSnapVertical` | `true` | Rise and sink with the right thumbstick |
| `maxTeleportDistance` | 10 | The furthest a teleport can go, in meters |
| `groundHeight` | 0 | The height of the flat ground that teleports land on |
| `teleportArcSpeed` | 8 | The speed the arc is thrown at. A faster arc reaches further |
| `validTeleportColor`, `invalidTeleportColor` | Pale blue, red | The colors of the arc where the user can and can't land |

Other attributes set the height of each vertical step, the thumbsticks' thresholds, and the width, detail and landing ring of the arc.

### Landing on Your Geometry

By default, teleports land on a flat plane at `groundHeight`. For uneven ground, steps or platforms, set the script's `castRay` function. The script calls it with the start and end of each segment of the arc in world space, in turn from the hand outward, and the arc lands at the first point it returns. With [physics](https://developer.playcanvas.com/user-manual/physics.md), cast each segment into the physics world:

```javascript
const navigation = rig.script.xrNavigation;
const from = new Vec3();
const lastEnd = new Vec3();
let blocked = false;

navigation.castRay = (start, end) => {
    // Each segment starts where the last one ended, so a segment that doesn't starts a new arc
    if (!start.equals(lastEnd)) blocked = false;
    lastEnd.copy(end);
    if (blocked) return null;

    // Cast from 5 cm before the segment, as a ray that starts on a surface can miss it
    from.sub2(start, end).normalize().mulScalar(0.05).add(start);
    const result = app.systems.rigidbody.raycastFirst(from, end);
    if (!result) return null;

    // Land on surfaces that face up, such as floors and steps
    if (result.normal.y > 0.7) return result.point;

    // Anything else, such as a wall, stops the arc
    blocked = true;
    return null;
};
```

`castRay` replaces the flat plane. When it returns `null`, the arc carries on to its next segment, so an arc that meets a wall would carry on through it, and land behind it. That's why the function above remembers that the arc has hit a wall, and returns `null` for the rest of it. To let users land on some surfaces only, [filter the ray cast](https://developer.playcanvas.com/user-manual/physics/ray-casting.md) by collision group or tag. `castRay` is a function, which can't be a script attribute, so set it from code in the Editor, React and Web Components too.

When your code moves the rig onto another floor itself, set the script's `currentGroundHeight` to that floor's height. Teleports keep the user's height above the floor they stand on.

### Teleporting and Menus

The script teleports whenever a select ends with the arc on valid ground. That includes a select that clicks a button or a menu item, so turn teleporting off while users interact with the interface:

```javascript
const navigation = rig.script.xrNavigation;
let menuOpen = false;

// XrMenu fires this as its menu opens and closes
app.on('xr:menu:active', (active) => {
    menuOpen = active;
});

app.on('update', () => {
    // No teleporting while a menu is open, or a ray points at an element
    const pointingAtUi = app.xr.input.inputSources.some((inputSource) => inputSource.elementEntity);
    navigation.enableTeleport = !menuOpen && !pointingAtUi;
});
```

`elementEntity` is the entity of the element that an input source points at, or `null`. See [UI in XR](https://developer.playcanvas.com/user-manual/user-interface/xr.md#pointing-and-selecting).

## Moving the World

Rather than moving the user through the scene, you can let them move the scene. The [`XrManipulation`](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md#grabbing-the-world) script lets users grab the scene with both hands to move, turn and scale it, which suits models and maps that they look at from every side.

## Comfort

When users see themselves move while their body feels still, some of them feel sick. These guidelines keep movement comfortable for most people:

- **Prefer teleporting and snap turns.** They show no movement, so they suit nearly everyone. Offer smooth movement and turning as options for users who like them. `XrNavigation` moves smoothly with the left thumbstick unless `enableMove` is `false`, and turns smoothly only when `turnMode` is `'smooth'`.
- **Move only when the user asks.** Don't move or turn the rig on your own, for example to show the user something. If you must, fade the view to black, move, and fade it back in.
- **Keep speeds steady.** Changes of speed are less comfortable than speed itself. Start and stop smooth movement at once, at a moderate speed, such as the default of 1.5 meters per second.
- **Keep the horizon level.** Turn the rig only about the vertical axis, and never roll or pitch it.
- **Keep the frame rate up.** Dropped frames make any movement worse. See [Performance](https://developer.playcanvas.com/user-manual/xr/optimizing-webxr.md).

## See Also

- [Sessions](https://developer.playcanvas.com/user-manual/xr/sessions.md#the-camera-and-its-rig) - The camera rig and reference spaces
- [Pointing and Grabbing](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md) - Grabbing objects, and the scene
- [Controllers](https://developer.playcanvas.com/user-manual/xr/controllers.md#buttons-and-thumbsticks) - Reading the thumbsticks yourself
- [UI in XR](https://developer.playcanvas.com/user-manual/user-interface/xr.md) - Menus and panels alongside teleporting
