First-person camera demo

WASD movement + mouse-look.

▶ Run in browser

Tags: 3d

Demonstrates:

  • Free-look camera driven by Input.mouse_delta (yaw + pitch)

  • WASD planar movement relative to camera heading

  • Click on the window to grab focus and start mouse-look (the cursor is locked / hidden via MouseCaptureMode.CAPTURED); press Escape to release the cursor and quit.

Controls: Click window - Enable mouse-look (locks the cursor to the window) Mouse - Look around (yaw / pitch) W A S D - Move (forward / left / back / right) Space - Up Ctrl - Down Shift - Sprint Escape - Quit

Run: uv run python examples/features/3d/first_person.py

Source

  1"""First-person camera demo: WASD movement + mouse-look.
  2
  3Demonstrates:
  4  - Free-look camera driven by ``Input.mouse_delta`` (yaw + pitch)
  5  - WASD planar movement relative to camera heading
  6  - Click on the window to grab focus and start mouse-look (the cursor is
  7    locked / hidden via ``MouseCaptureMode.CAPTURED``); press Escape to
  8    release the cursor and quit.
  9
 10Controls:
 11    Click window  - Enable mouse-look (locks the cursor to the window)
 12    Mouse         - Look around (yaw / pitch)
 13    W A S D       - Move (forward / left / back / right)
 14    Space         - Up
 15    Ctrl          - Down
 16    Shift         - Sprint
 17    Escape        - Quit
 18
 19Run: uv run python examples/features/3d/first_person.py
 20"""
 21
 22from __future__ import annotations
 23
 24import math
 25
 26from simvx.core import (
 27    Camera3D,
 28    DirectionalLight3D,
 29    Input,
 30    InputMap,
 31    Key,
 32    Material,
 33    Mesh,
 34    MeshInstance3D,
 35    MouseButton,
 36    MouseCaptureMode,
 37    Node,
 38    Text2D,
 39    Vec3,
 40    WorldEnvironment,
 41)
 42from simvx.graphics import App
 43
 44MOUSE_SENSITIVITY = 0.0025
 45MOVE_SPEED = 4.5
 46SPRINT_MULT = 2.0
 47PITCH_LIMIT = math.radians(85.0)
 48
 49
 50class FirstPersonScene(Node):
 51    def on_ready(self):
 52        InputMap.add_action("quit", [Key.ESCAPE])
 53        InputMap.add_action("fwd", [Key.W])
 54        InputMap.add_action("back", [Key.S])
 55        InputMap.add_action("left", [Key.A])
 56        InputMap.add_action("right", [Key.D])
 57        InputMap.add_action("up", [Key.SPACE])
 58        InputMap.add_action("down", [Key.LEFT_CONTROL, Key.RIGHT_CONTROL])
 59        InputMap.add_action("sprint", [Key.LEFT_SHIFT, Key.RIGHT_SHIFT])
 60        InputMap.add_action("look_start", [MouseButton.LEFT])
 61
 62        env = self.add_child(WorldEnvironment())
 63        env.bloom_enabled = False
 64        env.ambient_light_energy = 0.5
 65
 66        sun = DirectionalLight3D(position=(5, 12, 4))
 67        sun.intensity = 1.2
 68        sun.look_at(Vec3(0, 0, 0))
 69        self.add_child(sun)
 70
 71        # Camera state: yaw / pitch tracked explicitly so mouse_delta
 72        # accumulates instead of replacing rotation each frame.
 73        self._yaw = 0.0
 74        self._pitch = 0.0
 75        self._looking = False
 76        # Spawn in an empty checkerboard cell so the opening frame shows the
 77        # coloured obstacle grid rather than the top of the nearest cube.
 78        self._cam = self.add_child(Camera3D(
 79            position=(1.5, 1.7, 8), fov=70.0, near=0.05, far=200.0,
 80        ))
 81        self._apply_look()
 82
 83        # World geometry: a checkerboard of obstacles so motion reads.
 84        self.add_child(MeshInstance3D(
 85            mesh=Mesh.cube(size=1.0),
 86            material=Material(colour=(0.18, 0.2, 0.22, 1.0)),
 87            position=(0, -0.05, 0),
 88            scale=Vec3(60, 0.1, 60),
 89            name="Ground",
 90        ))
 91        palette = [
 92            (0.8, 0.3, 0.3, 1.0),
 93            (0.3, 0.7, 0.4, 1.0),
 94            (0.3, 0.5, 0.9, 1.0),
 95            (0.9, 0.7, 0.2, 1.0),
 96        ]
 97        for i in range(-4, 5):
 98            for j in range(-4, 5):
 99                if (i + j) % 2 == 0:
100                    continue
101                self.add_child(MeshInstance3D(
102                    mesh=Mesh.cube(size=1.0),
103                    material=Material(colour=palette[(i * 3 + j) % 4], roughness=0.6),
104                    pivot="bottom",
105                    position=(i * 3.0, 0.0, j * 3.0),
106                    scale=Vec3(1.0, 1.0 + (i + j) % 3 * 0.5, 1.0),
107                ))
108
109        self._hud = self.add_child(Text2D(
110            text=(
111                "First-person camera demo\n"
112                "Click window to start looking; WASD move; Shift sprint; Esc quit."
113            ),
114            position=(12, 12), font_scale=1.1, colour=(1, 1, 1, 1),
115        ))
116
117    def on_update(self, dt: float):
118        if Input.is_action_just_pressed("quit"):
119            Input.set_mouse_capture_mode(MouseCaptureMode.VISIBLE)
120            self.app.quit()
121            return
122
123        if Input.is_action_just_pressed("look_start"):
124            self._looking = True
125            Input.set_mouse_capture_mode(MouseCaptureMode.CAPTURED)
126
127        if self._looking:
128            md = Input.mouse_delta
129            if md.x or md.y:
130                self._yaw -= float(md.x) * MOUSE_SENSITIVITY
131                self._pitch -= float(md.y) * MOUSE_SENSITIVITY
132                self._pitch = max(-PITCH_LIMIT, min(PITCH_LIMIT, self._pitch))
133                self._apply_look()
134
135        # Movement relative to the camera's horizontal heading.
136        forward_h = Vec3(math.sin(self._yaw), 0.0, math.cos(self._yaw))
137        right_h = Vec3(math.cos(self._yaw), 0.0, -math.sin(self._yaw))
138
139        move = Vec3(0, 0, 0)
140        if Input.is_action_pressed("fwd"):
141            move = move - forward_h
142        if Input.is_action_pressed("back"):
143            move = move + forward_h
144        if Input.is_action_pressed("right"):
145            move = move + right_h
146        if Input.is_action_pressed("left"):
147            move = move - right_h
148        if Input.is_action_pressed("up"):
149            move = move + Vec3(0, 1, 0)
150        if Input.is_action_pressed("down"):
151            move = move - Vec3(0, 1, 0)
152
153        if move.length() > 1e-5:
154            speed = MOVE_SPEED * (SPRINT_MULT if Input.is_action_pressed("sprint") else 1.0)
155            move = move.normalized() * (speed * dt)
156            self._cam.position = self._cam.position + move
157
158    def _apply_look(self) -> None:
159        """Recompute camera world rotation from yaw + pitch state."""
160        # yaw rotates around +Y, pitch around right (post-yaw +X).
161        # Compose by setting world_rotation = Y(yaw) * X(pitch).
162        from simvx.core import Quat
163
164        q_yaw = Quat.from_axis_angle(Vec3(0, 1, 0), self._yaw)
165        q_pitch = Quat.from_axis_angle(Vec3(1, 0, 0), self._pitch)
166        self._cam.world_rotation = q_yaw * q_pitch
167
168
169if __name__ == "__main__":
170    App(title="First-Person Camera", width=1280, height=720).run(FirstPersonScene())