Skip to content

Cookbook

Pick and drag ​

Pick up a mesh with the pointer and move it across the floor, with an orbiting camera that stays out of the way.

Dragging takes two kinds of ray test. On the press, a Raycast from the pointer into the scene finds the mesh under it, and the exact point it was grabbed by. While the pointer moves, the same ray is tested against a flat plane through that point instead, which gives the point to move the mesh to. The plane is level, so the mesh slides across the floor at its own height, whatever the camera's angle.

Drag a shape to move it. Drag the floor to turn the camera.

js
import {
  Renderer,
  DollyCamera,
  Obj,
  Mesh,
  Lights,
  LitProgram,
  Shadow,
  Raycast,
  Plane,
  Box,
  Sphere,
  Cylinder,
  Vec2,
  Vec3
} from 'wtc-gl'

// Drag the shapes around the floor; drag the floor to orbit. A Raycast picks
// the shape under the pointer, then follows the pointer across a flat plane.
export default function (container) {
  const renderer = new Renderer({
    dpr: Math.min(devicePixelRatio, 2),
    alpha: true,
    premultipliedAlpha: true,
    antialias: true,
    clearColour: [0, 0, 0, 0]
  })
  const { gl } = renderer
  const canvas = gl.canvas
  // Touches drag the shapes rather than scroll the page
  canvas.style.touchAction = 'none'
  container.appendChild(canvas)

  // No wheel zoom, so the page still scrolls over the example
  const camera = new DollyCamera(
    {
      element: canvas,
      enableZoom: false,
      enablePan: false,
      maxPolarAngle: 1.3
    },
    { fov: 35 }
  )
  camera.setPosition(0, 6, 9)
  const scene = new Obj()
  const lights = new Lights({ direction: [0.4, 1, 0.3], ambient: 0.15 })
  const shadow = new Shadow(gl, { lights, size: 5 })

  const floor = new Mesh(gl, {
    geometry: new Plane(gl, { width: 8, height: 8 }),
    program: new LitProgram(gl, { lights, shadow, colour: [0.85, 0.83, 0.8] })
  })
  floor.rotation.x = -Math.PI / 2
  floor.updateRotation()
  floor.setParent(scene)

  const geometries = [
    [new Box(gl, { width: 0.9, height: 0.9, depth: 0.9 }), 0.45],
    [new Sphere(gl, { radius: 0.5, widthSegments: 32 }), 0.5],
    [
      new Cylinder(gl, {
        radiusTop: 0.4,
        radiusBottom: 0.4,
        radialSegments: 32
      }),
      0.5
    ]
  ]
  const colours = [
    [0.95, 0.42, 0.26],
    [0.3, 0.45, 0.85],
    [0.5, 0.74, 0.45]
  ]
  const pieces = Array.from({ length: 6 }, (_, i) => {
    const [geometry, y] = geometries[i % 3]
    const mesh = new Mesh(gl, {
      geometry,
      program: new LitProgram(gl, { lights, shadow, colour: colours[i % 3] })
    })
    mesh.position.reset((i % 3) * 1.6 - 1.6, y, i < 3 ? -0.9 : 0.9)
    mesh.setParent(scene)
    shadow.add(mesh)
    return mesh
  })

  const raycast = new Raycast()
  const up = new Vec3(0, 1, 0)
  const planePoint = new Vec3()
  const offset = new Vec3()
  const hit = new Vec3()
  let dragging = null

  const cast = (e) => {
    const rect = canvas.getBoundingClientRect()
    const x = ((e.clientX - rect.left) / rect.width) * 2 - 1
    const y = 1 - ((e.clientY - rect.top) / rect.height) * 2
    return raycast.castMouse(camera, [x, y])
  }
  const onDown = (e) => {
    const [picked] = cast(e).intersectMeshes(pieces)
    if (!picked) return // a miss falls through to the camera
    dragging = picked.mesh
    // Drag across the level plane through the point that was grabbed, and
    // keep the gap to the mesh's centre so it doesn't jump
    planePoint.resetToVector(picked.point)
    offset.resetToVector(dragging.position).subtract(picked.point)
    camera.enabled = false
    canvas.setPointerCapture(e.pointerId)
    dragging.program.emissive = [0.25, 0.25, 0.25]
  }
  const onMove = (e) => {
    if (!dragging) return
    if (!cast(e).intersectPlane(up, planePoint, hit)) return
    const limit = 3.5
    dragging.position.x = Math.max(-limit, Math.min(limit, hit.x + offset.x))
    dragging.position.z = Math.max(-limit, Math.min(limit, hit.z + offset.z))
  }
  const onUp = () => {
    if (!dragging) return
    dragging.program.emissive = [0, 0, 0]
    dragging = null
    camera.enabled = true
  }
  canvas.addEventListener('pointerdown', onDown)
  canvas.addEventListener('pointermove', onMove)
  canvas.addEventListener('pointerup', onUp)
  canvas.addEventListener('pointercancel', onUp)

  return {
    frame() {
      camera.update()
      shadow.render({ scene })
      renderer.render({ scene, camera })
    },
    resize(width, height) {
      renderer.dimensions = new Vec2(width, height)
      camera.perspective({ aspect: width / height })
    },
    dispose() {
      canvas.removeEventListener('pointerdown', onDown)
      canvas.removeEventListener('pointermove', onMove)
      canvas.removeEventListener('pointerup', onUp)
      canvas.removeEventListener('pointercancel', onUp)
      camera.removeHandlers()
      for (const [geometry] of geometries) geometry.remove()
      for (const mesh of [floor, ...pieces]) mesh.program.remove()
      floor.geometry.remove()
      shadow.remove()
      renderer.dispose()
      canvas.remove()
    }
  }
}

Casting from the pointer ​

Both tests start the same way: work out the pointer in normalised device coordinates, -1 to 1 across the canvas with y up, and cast from the camera through it:

js
const cast = (e) => {
  const rect = canvas.getBoundingClientRect()
  const x = ((e.clientX - rect.left) / rect.width) * 2 - 1
  const y = 1 - ((e.clientY - rect.top) / rect.height) * 2
  return raycast.castMouse(camera, [x, y])
}

castMouse returns the raycast, so a test can follow it straight away.

Picking up ​

On pointerdown, test the meshes that can be dragged. intersectMeshes returns the hits nearest first, so the first is the one on top:

js
const onDown = (e) => {
  const [picked] = cast(e).intersectMeshes(pieces)
  if (!picked) return
  dragging = picked.mesh
  planePoint.resetToVector(picked.point)
  offset.resetToVector(dragging.position).subtract(picked.point)
  camera.enabled = false
  canvas.setPointerCapture(e.pointerId)
}

Two things are kept from the hit:

  • planePoint, where the mesh was grabbed. The drag plane passes through it, so the pointer stays on the same spot of the mesh as it moves, rather than on the floor beneath it.
  • offset, from the grabbed point to the mesh's position. Without it, the mesh's centre would jump to the pointer on the first move.

Pass only the meshes that can be dragged, not the whole scene, so the floor and anything else can't be picked up. For simple shapes, intersectBounds is cheaper and, with padding, easier to hit when they're small.

Dragging across a plane ​

On pointermove, cast again and meet the plane through planePoint, facing up:

js
const up = new Vec3(0, 1, 0)
const hit = new Vec3()

const onMove = (e) => {
  if (!dragging) return
  if (!cast(e).intersectPlane(up, planePoint, hit)) return
  dragging.position.x = hit.x + offset.x
  dragging.position.z = hit.z + offset.z
}

intersectPlane writes into hit instead of making a new vector, and returns null when the ray runs parallel to the plane or points away from it, as it can when the pointer goes above the horizon. Keep the mesh where it was then. Clamp the position, as the example does, to keep the mesh on the floor.

Other planes give other drags:

  • A plane facing the camera moves a mesh up and down the screen as well as across it. The camera's backward axis is the third column of its world matrix: new Vec3(m.a31, m.a32, m.a33) with m = camera.worldMatrix. The paths demo drags its handles this way.
  • A vertical plane through the grabbed point, facing the camera horizontally, lifts a mesh without moving it across the floor.

Pointer capture ​

setPointerCapture sends the pointer's later events to the canvas even after it leaves, so a fast drag that overshoots the canvas edge keeps going, and the release is still seen. The capture ends by itself on pointerup. Listen for pointercancel too, which the browser sends if it takes the pointer back, and end the drag on either:

js
const onUp = () => {
  dragging = null
  camera.enabled = true
}
canvas.addEventListener('pointerup', onUp)
canvas.addEventListener('pointercancel', onUp)

Keeping the camera still ​

A DollyCamera listening on the same canvas would turn as the mesh is dragged. Set camera.enabled = false when a drag starts and back to true when it ends. The camera listens for mousedown and touchstart, which arrive after pointerdown, so it's already off by the time it sees the press. A press that misses every mesh leaves it on, so dragging the empty floor still orbits.

The camera's own touch handling is what stops the page scrolling under a finger, and that's off during a drag, so set touch-action: none on the canvas. In a page that scrolls, also turn off enableZoom, since the camera takes the wheel for zooming and the page won't scroll under the pointer.

Picking, between frames ​

Pointer events arrive between frames, and a ray test uses the world matrices from the last render, which is what's on screen. That's what you want here. If you move meshes and test again before the next render, call scene.updateMatrixWorld() first.

See also ​