A character controller: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: model (line 50), floor (line 61), controller (line 64), walk (line 69), body (line 105), check (line 139).
1/// A capsule-shaped walker, dropped onto a floor and pushed sideways,
2/// stepped by hand a few dozen times rather than once, so it actually lands.
3/// The collider stays the plain box `CharacterController` gives one by
4/// default — see `character_controller.md` for why — but what stands on it
5/// is `RobotExpressive.glb` rather than the crate that used to mark its
6/// place, so a reader watches an actual character land and walk.
7///
8/// Quoted by `character_controller.md` and shown whole in the Source tab.
9library;
11import 'dart:math' as math;
13import 'package:flutter3d/flutter3d.dart';
14import 'package:flutter3d_physics/flutter3d_physics.dart';
15import 'package:flutter3d_showcase/src/demo/demo.dart';
16import 'package:flutter3d_showcase/src/demo/run_physics.dart';
18/// The `character-controller` page: the robot standing on a
19/// `CharacterController`, dropped onto a floor and pushed towards +x. Its
20/// check is that it landed on a flat ground normal and moved along +x.
21final class CharacterControllerDemo extends ShowcaseDemo {
22 late final CollisionWorld _world;
23 late final CharacterController _controller;
24 late final ModelAsset _asset;
25 ModelInstance? _model;
27 static const double _step = 1 / 60;
28 static const int _steps = 90;
30 /// `RobotExpressive.glb` stands this tall in its own file — measured once,
31 /// off the mesh it ships with — so [_characterHeight] can scale it to the
32 /// collider's own box without carrying a decoded model around just to ask.
33 static const double _modelHeight = 4.461221901699901;
35 /// What the collider's box already claimed: `CharacterController`'s
36 /// default shape is `CollisionBox(Vector3(0.35, 0.9, 0.35))`, 1.8 m tall.
37 static const double _characterHeight = 1.8;
40 void configureView(DemoContext context) {
41 // Distance and target are set again in `build`, once the walk has run
42 // and there is somewhere to actually point the camera at.
43 context.orbit
44 ..pitch = 0.2
45 ..yaw = 0.6;
46 }
49 Future<void> prepare(DemoContext context) async {
50 // CC0 — Tomás Laulhé, with facial morph targets by Don McCurdy; see
51 // `packages/flutter3d_samples/assets/ATTRIBUTION.md`. Fourteen clips ship
52 // in the one file, and "Walking" is the one this page plays.
53 final document = await loadModelByPath(
54 'packages/flutter3d_samples/assets/RobotExpressive.glb',
55 );
56 _asset = await ModelAsset.fromDocument(document, device: context.device);
57 }
60 Scene build(DemoContext context) {
61 _world = onRunPhysics(CollisionWorld());
62 _world.addBox(Vector3(0.0, -0.5, 0.0), Vector3(20.0, 1.0, 20.0));
64 _controller = CharacterController(
65 world: _world,
66 position: Vector3(0.0, 3.0, 0.0),
67 );
69 // Stepped by hand, at a fixed rate, so the same run always lands the
70 // same way. A real game calls this once a frame with the frame's own
71 // wish direction; a page rendered once has to do all its steps up front.
72 for (var i = 0; i < _steps; i++) {
73 _controller.step(_step, wishDirection: Vector3(1.0, 0.0, 0.0));
74 }
76 // The walk covers several metres of +x, and `configureView` runs before
77 // any of it — orbiting the origin left the walker's actual resting place
78 // well outside the frame. This page draws a single, already-landed
79 // frame rather than the walk itself, so what needs framing is where the
80 // walker actually ended up, not where it started.
81 context.orbit
82 ..target.setValues(_controller.position.x, 0.9, 0.0)
83 ..distance = 5.0
84 ..apply();
86 final Scene scene = Scene()
87 ..add(
88 MeshNode(
89 DeviceMesh.upload(
90 context.device,
91 CuboidShape(size: Vector3(20.0, 1.0, 20.0)).build(),
92 ),
93 RenderMaterial(
94 name: 'floor',
95 baseColor: LinearColor.fromSrgb(0.5, 0.55, 0.5, 1.0),
96 ),
97 name: 'floor',
98 )..setPosition(0.0, -0.5, 0.0),
99 )
100 ..add(
101 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
102 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
103 );
105 // The model's own origin sits at its feet, not its centre, and it faces
106 // +Z at rest; turned a quarter-turn around Y so it faces the +X the walk
107 // above actually carried it towards, then dropped onto the box's own
108 // centre minus half its height, the ground the box already stands on.
109 final ModelInstance model = _model = _asset.instantiate(
110 scene,
111 name: 'walker',
112 );
113 final double scale = _characterHeight / _modelHeight;
114 model.root
115 ..setScale(scale, scale, scale)
116 ..setRotation(Quaternion.axisAngle(Vector3(0.0, 1.0, 0.0), -math.pi / 2));
117 model.player?.playNamed('Walking');
119 _placeModel();
120 return scene;
121 }
123 void _placeModel() {
124 final ModelInstance? model = _model;
125 if (model == null) return;
126 final Vector3 position = _controller.position;
127 final double feetY = position.y - _controller.halfExtents.y;
128 model.root.setPosition(position.x, feetY, position.z);
129 }
132 void update(DemoContext context, double dt) {
133 _placeModel();
134 _model?.player?.advance(dt);
135 }
138 void verify(Scene scene, FrameResult frame) {
139 if (!_controller.isGrounded) {
140 throw StateError('the walker should have landed by now');
141 }
142 if (_controller.groundNormal.y < 0.99) {
143 throw StateError('a flat floor should read as a flat ground normal');
144 }
145 if (_controller.position.x <= 0.0) {
146 throw StateError('the walker should have moved towards +x');
147 }
148 if (_model == null || _model!.meshes.isEmpty) {
149 throw StateError('the model did not reach the scene');
150 }
151 if (frame.drawCalls < 1) {
152 throw StateError('the walker did not reach the frame');
153 }
154 }
155}