# Pointing and Grabbing

Most interaction in XR comes down to a few actions: point at something and select it, reach out and grab it, throw it, or press it with a finger. This page builds each one from the [rays, actions and poses](https://developer.playcanvas.com/user-manual/xr/input-sources.md) of input sources. The code works in VR and AR, with controllers and with tracked hands.

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

[Live example: XR Picking](https://playcanvas.com/examples/#/xr/xr-picking) ([source](https://github.com/playcanvas/engine/blob/main/examples/src/examples/xr/xr-picking/example.mjs))

## Pointing

To find what the user points at, test the ray of their input source against the objects they can interact with. There are two common ways: against the objects' bounding boxes, or, with physics, against their collision shapes.

### With Bounding Boxes

For a few objects, test the ray against the bounding box of each one's meshes. This function finds the closest object that an input source points at:

```javascript
const ray = new Ray();
const point = new Vec3();

// The closest of the entities that the input source points at, or null.
// The point where the ray meets it is copied to hitPoint.
const pick = (inputSource, entities, hitPoint) => {
    ray.set(inputSource.getOrigin(), inputSource.getDirection());

    let closest = null;
    let closestDistance = Infinity;
    for (const entity of entities) {
        for (const meshInstance of entity.render.meshInstances) {
            if (meshInstance.aabb.intersectsRay(ray, point)) {
                const distance = point.distance(ray.origin);
                if (distance < closestDistance) {
                    closest = entity;
                    closestDistance = distance;
                    hitPoint.copy(point);
                }
            }
        }
    }
    return closest;
};
```

A bounding box is aligned with the world's axes, so it is larger than a rotated or round object, and the ray can hit the box where the object isn't. For more precise picking, or many objects, use physics.

### With Physics

With [physics](https://developer.playcanvas.com/user-manual/physics.md) in your application, cast the ray into the physics world. It tests the collision shapes of entities, which can follow their meshes closely:

```javascript
const end = new Vec3();

// The physics ray cast result for what the input source points at, within ten meters, or null
const pickWithPhysics = (inputSource) => {
    const origin = inputSource.getOrigin();
    end.copy(inputSource.getDirection()).mulScalar(10).add(origin);
    return app.systems.rigidbody.raycastFirst(origin, end);
};
```

The result has the `entity` that the ray hit, and the `point` and `normal` where it hit. See [Ray Casting](https://developer.playcanvas.com/user-manual/physics/ray-casting.md) for filtering what a ray can hit.

## Selecting

Pick when the user selects, to act on what they point at:

```javascript
const hitPoint = new Vec3();

app.xr.input.on('select', (inputSource) => {
    const target = pick(inputSource, targets, hitPoint);
    if (target) {
        console.log(`Selected ${target.name}`);
    }
});
```

`select` fires when the select completes, as the user releases the trigger or opens the pinch. That works for any input source, including a touch on a phone's screen and a look and a pinch on an Apple Vision Pro.

## Showing the Ray

A visible ray shows users where they point, and highlighting its target shows them what a select will hit. This draws a line from each controller and hand, to what it points at or two meters out, in yellow while it points at something:

```javascript
const lineEnd = new Vec3();

app.on('update', () => {
    for (const inputSource of app.xr.input.inputSources) {
        // Touches and look-and-pinch are brief, and need no ray
        if (inputSource.targetRayMode !== XRTARGETRAY_POINTER) continue;

        const target = pick(inputSource, targets, lineEnd);
        if (!target) {
            lineEnd.copy(inputSource.getDirection()).mulScalar(2).add(inputSource.getOrigin());
        }
        app.drawLine(inputSource.getOrigin(), lineEnd, target ? Color.YELLOW : Color.WHITE);
    }
});
```

`app.drawLine()` draws a line one pixel wide for one frame. For a laser that is easier to see, draw a long, thin box, or a mesh of your own, and stretch it in the same way. To highlight the target itself, change its material while the ray is on it.

## Grabbing

To grab an object, remember where it is relative to the hand when the squeeze starts, and keep it there until the squeeze ends. Controllers hold things at their [grip pose](https://developer.playcanvas.com/user-manual/xr/controllers.md#the-grip-pose). Hands have no grip pose, so this uses the wrist of a hand instead:

```javascript
const held = new Map(); // each input source's grab: { entity, offset }
const hold = new Mat4();
const world = new Mat4();
const position = new Vec3();
const rotation = new Quat();

// Where an input source holds things, as a world transform: a controller's grip, or a hand's wrist
const getHoldTransform = (inputSource, result) => {
    if (inputSource.grip) {
        return result.setTRS(inputSource.getPosition(), inputSource.getRotation(), Vec3.ONE);
    }
    const wrist = inputSource.hand?.wrist;
    return wrist ? result.setTRS(wrist.getPosition(), wrist.getRotation(), Vec3.ONE) : null;
};

// The closest grabbable object within 15 cm of a point, or null
const findGrabbable = (point) => {
    let closest = null;
    let closestDistance = 0.15;
    for (const entity of grabbables) {
        const distance = entity.getPosition().distance(point);
        if (distance < closestDistance) {
            closest = entity;
            closestDistance = distance;
        }
    }
    return closest;
};

app.xr.input.on('squeezestart', (inputSource) => {
    if (!getHoldTransform(inputSource, hold)) return;
    const entity = findGrabbable(hold.getTranslation(position));
    if (!entity) return;

    // Remember where the object is relative to the hand
    const offset = new Mat4().mul2(hold.invert(), entity.getWorldTransform());
    held.set(inputSource, { entity, offset });
});

const release = (inputSource) => {
    held.delete(inputSource);
};
app.xr.input.on('squeezeend', release);
app.xr.input.on('remove', release);

app.on('update', () => {
    // Keep each held object where it was in the hand
    for (const [inputSource, { entity, offset }] of held) {
        if (!getHoldTransform(inputSource, hold)) continue;
        world.mul2(hold, offset);
        entity.setPosition(world.getTranslation(position));
        entity.setRotation(rotation.setFromMat4(world));
    }
});
```

An input source can be removed while it holds something, for example when the user puts a controller down, so this releases what it holds on `remove` too. A held object follows the hand wherever the rig takes it, so users can carry things as they move around. To grab from a distance, pick the object with the [ray](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md#pointing) instead of looking for one near the hand.

## Throwing

An object that falls and bounces when the user lets go of it needs a dynamic [rigid body](https://developer.playcanvas.com/user-manual/physics/rigid-bodies.md). Physics moves dynamic bodies, and overrides their entity's transform, so make the body kinematic while it is held. A kinematic body follows its entity, and pushes dynamic bodies out of its way. When the user lets go, make the body dynamic again, with the velocity it was moving at.

Controllers report their [velocity](https://developer.playcanvas.com/user-manual/xr/controllers.md#velocity), but hands don't, and a controller's velocity doesn't include the movement of the rig. So measure the velocity of the held object instead, which works for both. These handlers replace the `squeezestart`, `squeezeend`, `remove` and `update` handlers of [Grabbing](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md#grabbing), and use its other functions:

```javascript
app.xr.input.on('squeezestart', (inputSource) => {
    if (!getHoldTransform(inputSource, hold)) return;
    const entity = findGrabbable(hold.getTranslation(position));
    if (!entity) return;

    const offset = new Mat4().mul2(hold.invert(), entity.getWorldTransform());
    held.set(inputSource, { entity, offset, last: entity.getPosition().clone(), velocity: new Vec3() });

    // Physics stops moving the body while it is held
    entity.rigidbody.type = BODYTYPE_KINEMATIC;
});

const step = new Vec3();

app.on('update', (dt) => {
    for (const [inputSource, grab] of held) {
        if (!getHoldTransform(inputSource, hold)) continue;
        world.mul2(hold, grab.offset);
        grab.entity.setPosition(world.getTranslation(position));
        grab.entity.setRotation(rotation.setFromMat4(world));

        // Measure the object's velocity, smoothed over the last few frames
        if (dt > 0) {
            step.sub2(position, grab.last).divScalar(dt);
            grab.velocity.lerp(grab.velocity, step, 0.5);
        }
        grab.last.copy(position);
    }
});

// Throw the object when the user lets go
const release = (inputSource) => {
    const grab = held.get(inputSource);
    if (!grab) return;
    held.delete(inputSource);

    const body = grab.entity.rigidbody;
    body.type = BODYTYPE_DYNAMIC;
    body.linearVelocity = grab.velocity;
};
app.xr.input.on('squeezeend', release);
app.xr.input.on('remove', release);
```

Smoothing the velocity over a few frames evens out the jitter of tracking. Because the velocity is the object's own, it includes any movement of the rig, and the object's movement as the user turns their hand.

## Pressing with a Fingertip

For buttons within reach, a fingertip is more direct than a ray. Press when the tip of an index finger comes close to a button, and release only once it has moved further away, so that a finger that trembles near the button doesn't press it again and again:

```javascript
let pressed = false;

app.on('update', () => {
    // The distance from the closest index fingertip to the button
    let distance = Infinity;
    for (const inputSource of app.xr.input.inputSources) {
        const tip = inputSource.hand?.getJointById('index-finger-tip');
        if (tip && inputSource.hand.tracking) {
            distance = Math.min(distance, tip.getPosition().distance(button.getPosition()));
        }
    }

    // Press within 2 cm of the button's center, and release beyond 4 cm
    if (!pressed && distance < 0.02) {
        pressed = true;
        console.log('Pressed the button');
    } else if (pressed && distance > 0.04) {
        pressed = false;
    }
});
```

For a flat button, measure the distance along the button's normal instead, so that the finger has to push into its face. The [`XrMenu`](https://developer.playcanvas.com/user-manual/user-interface/xr.md#xr-menus) script's buttons work with fingertips as well as rays.

## Grabbing the World

The engine's `XrManipulation` script lets users move, turn and scale the scene, rather than one object. They squeeze both grips, or make fists with both hands, and then:

- **Move both hands the same way** to drag the scene in any direction.
- **Swing their hands around each other** to turn it about the vertical axis.
- **Move their hands apart or together** to scale it up or down.

It suits models, maps and dioramas that users look at from every side. The script moves, turns and scales a target entity, under which you put the content. It doesn't change the rig, so controllers, hands and menus keep their real size.

**Engine**

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

// The content to manipulate, under an entity of its own
const world = new Entity('world');
world.addChild(model);
app.root.addChild(world);

rig.script.create(XrManipulation, {
    properties: {
        target: world,
        minScale: 0.5,
        maxScale: 4
    }
});
```

**Editor**

1. Add `xr-manipulation.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. Put the content to manipulate under an entity of its own, such as `World`.
3. Select the rig, and add **xrManipulation** to its Script component.
4. Drag the `World` entity from the Hierarchy onto the script's **Target** attribute, and set its other attributes.

**React**

The target is an entity, which an `<Entity>` passes to its `ref`:

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

export function ManipulatedScene({ children }) {
  const [world, setWorld] = useState(null);

  return (
    <>
      <Entity name="world" ref={setWorld}>
        {children}
      </Entity>
      <Entity name="rig">
        {/* the camera, and the rig's other scripts ... */}
        {world && <Script script={XrManipulation} target={world} minScale={0.5} maxScale={4} />}
      </Entity>
    </>
  );
}
```

**Web Components**

Declare the script in a `<pc-asset>` inside `<pc-app>`, and refer to the target entity by its name:

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

<pc-entity name="world">
    <!-- the content to manipulate ... -->
</pc-entity>
<pc-entity name="rig">
    <!-- the camera ... -->
    <pc-script>
        <pc-script-instance name="xrManipulation" target="entity:world" min-scale="0.5" max-scale="4"></pc-script-instance>
    </pc-script>
</pc-entity>
```

| Attribute | Default | Description |
| --- | --- | --- |
| `target` | | The entity to move, turn and scale |
| `enableTranslate`, `enableRotate`, `enableScale` | `true` | Which of the three the user can do |
| `minScale`, `maxScale` | 0.2, 5 | The smallest and largest scale, relative to the target's scale when the script starts |
| `scalePivot` | `'feet'` | `'feet'` keeps what is at the user's feet on the floor as the scene scales, for scenes the user stands in. `'hands'` scales about the point between the hands, for models on a table |
| `scaleThreshold` | 0.15 | How far the hands must move apart or together, as a fraction of the distance between them, before scaling starts |
| `resetEvent` | `'xr:manipulation:reset'` | The application event that puts the target back where it started |

The target keeps its new transform when the session ends. Fire the reset event, for example from a menu item, to put it back. The script fires `xr:manipulation:active` with `true` when a grab starts and `false` when it ends, and ignores grabs while an [`XrMenu`](https://developer.playcanvas.com/user-manual/user-interface/xr.md#xr-menus) is open.

Teleports land on a plane that stays where it is as the scene moves. See [Locomotion](https://developer.playcanvas.com/user-manual/xr/locomotion.md#landing-on-your-geometry) if users can move the scene up and down. Avoid putting rigid bodies under the target: primitive collision shapes ignore its scale, and mesh shapes are rebuilt each time it changes.

## See Also

- [Input Sources](https://developer.playcanvas.com/user-manual/xr/input-sources.md) - Rays, and the select and squeeze actions
- [Controllers](https://developer.playcanvas.com/user-manual/xr/controllers.md) - Grip poses and velocity
- [Hand Tracking](https://developer.playcanvas.com/user-manual/xr/hand-tracking.md) - The joints of tracked hands
- [Ray Casting](https://developer.playcanvas.com/user-manual/physics/ray-casting.md) - Casting rays into the physics world
- [UI in XR](https://developer.playcanvas.com/user-manual/user-interface/xr.md) - Pointing at and selecting UI elements
