Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qcharactercontroller.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
7
8#include "physxnode/qphysxcharactercontroller_p.h"
9
10#include <QtCore/QPointer>
11
13
14/*!
15 \qmltype CharacterController
16 \inqmlmodule QtQuick3D.Physics
17 \inherits PhysicsBody
18 \since 6.4
19 \brief Controls the motion of a character.
20
21 The CharacterController type controls the motion of a character.
22
23 A character is an entity that moves under external control, but is still constrained
24 by physical barriers and (optionally) subject to gravity. This is in contrast to
25 \l{DynamicRigidBody}{dynamic rigid bodies} which are either completely controlled by
26 the physics simulation (for non-kinematic bodies); or move exactly where placed,
27 regardless of barriers (for kinematic objects).
28
29 To control the motion of a character controller, set \l movement to the desired velocity.
30
31 For a first-person view, the camera is typically placed inside a character controller.
32
33 \note \l {PhysicsNode::collisionShapes}{collisionShapes} must be set to
34 a single \l {CapsuleShape}. No other shapes are supported.
35
36 \sa {Qt Quick 3D Physics Shapes, Bodies and Joints}
37*/
38
39/*!
40 \qmlproperty vector3d CharacterController::movement
41
42 This property defines the controlled motion of the character. This is the velocity the character
43 would move in the absence of gravity and without interacting with other physics objects.
44
45 This property does not reflect the actual velocity of the character. If the character is stuck
46 against terrain, the character can move slower than the speed defined by \c movement. Conversely, if the
47 character is in free fall, it may move much faster.
48
49 Default value: \c{(0, 0, 0)}
50*/
51
52/*!
53 \qmlproperty vector3d CharacterController::gravity
54
55 This property defines the gravitational acceleration that applies to the character.
56 For a character that walks on the ground, it should typically be set to
57 \l{PhysicsWorld::gravity}{PhysicsWorld.gravity}. A floating character that has movement
58 controls in three dimensions will normally have gravity \c{(0, 0, 0)}.
59
60 A \l GravityField adds its own gravity to this one: one without collision
61 shapes wherever the character is, and one with collision shapes for as
62 long as the character is inside them. A character that is to keep to its
63 own gravity while everything else falls, for instance one swimming or
64 climbing a ladder, is kept out of a field with
65 \l{PhysicsNode::filterGroup}{filterGroup} and
66 \l{PhysicsNode::filterIgnoreGroups}{filterIgnoreGroups}.
67
68 Setting this property to zero stops the character falling at once, which is
69 how a character grabs a ladder or enters water. Leaving a field's shapes
70 does not: the character keeps the speed it built up under the field's
71 gravity, with
72 \l movement applying as usual, until it lands on something.
73
74 \note The character's up direction, used for \l collisions, slopes, steps and
75 \l gravityOrientation, is opposite to this gravity plus the gravity of any
76 \l GravityField acting on it.
77
78 Default value: \c{(0, 0, 0)}.
79*/
80
81/*!
82 \qmlproperty bool CharacterController::midAirControl
83
84 This property defines whether the \l movement property has effect when the character is in free
85 fall. The character is in free fall while its own \l gravity or a \l GravityField is pulling
86 on it, or while it is still moving at the speed it built up under a field whose shapes it has
87 left. A value of \c true means that the character will change direction in
88 mid-air when \c movement changes. A value of \c false means that the character will continue
89 on its current trajectory until it hits another object.
90
91 Default value: \c true
92*/
93
94/*!
95 \qmlproperty Collisions CharacterController::collisions
96 \readonly
97
98 This property holds the current collision state of the character. It is either \c None for no
99 collision, or an OR combination of \c Side, \c Up, and \c Down:
100
101 \value CharacterController.None
102 The character is not touching anything. If gravity is non-null, this means that the
103 character is in free fall.
104 \value CharacterController.Side
105 The character is touching something on its side.
106 \value CharacterController.Up
107 The character is touching something above it.
108 \value CharacterController.Down
109 The character is touching something below it. In standard gravity, this means
110 that the character is on the ground.
111
112 The directions are relative to the character's up direction, which is opposite
113 to its gravity: \l gravity plus the gravity of any \l GravityField acting on it.
114 If that gravity is zero, the last up direction is kept.
115*/
116
117/*!
118 \qmlproperty bool CharacterController::enableShapeHitCallback
119 \since 6.6
120
121 This property enables/disables the \l {CharacterController::shapeHit} callback for this
122 character controller.
123
124 Default value: \c{false}
125*/
126
127/*!
128 \qmlmethod void CharacterController::teleport(vector3d position)
129 Immediately move the character to \a position without checking for collisions.
130 The caller is responsible for avoiding overlap with static objects.
131*/
132
133/*!
134 \qmlsignal CharacterController::shapeHit(PhysicsNode *body, vector3D position, vector3D impulse,
135 vector3D normal)
136 \since 6.6
137
138 This signal is emitted when \l {CharacterController::}{movement} has been
139 called and it would result
140 in a collision with a \l {DynamicRigidBody} or a \l {StaticRigidBody} and
141 \l {CharacterController::} {enableShapeHitCallback} is set to \c true.
142 The parameters \a body, \a position, \a impulse and \a normal contain the body, position,
143 impulse force and normal for the contact point.
144*/
145
146/*!
147 \qmlproperty real CharacterController::maximumStepHeight
148 \since 6.13
149
150 This property defines the maximum height step that the character controller can automatically
151 climb over when moving on a surface.
152
153 A value of \c 0 disables stepping. A negative value, which is the default,
154 makes the controller pick a step height from the size of its capsule.
155
156 The step height picked for a negative value is currently a quarter of
157 the capsule's height, but this may change in future versions. To keep a
158 fixed relation to the capsule, bind the property to it instead:
159
160 \qml
161 CharacterController {
162 maximumStepHeight: capsule.height * 0.25
163 collisionShapes: CapsuleShape { id: capsule }
164 }
165 \endqml
166
167 \default -1
168
169 \note When using a \l CapsuleShape, the rounded bottom of the capsule interacts with sharp step
170 edges as if they were inclined surfaces. As a result, the controller may scale steps higher
171 than the defined \c maximumStepHeight if the step height is smaller than the bottom sphere radius of
172 the capsule and the surface angle does not exceed \l slopeLimit.
173
174 \sa slopeLimit
175*/
176
177/*!
178 \qmlproperty real CharacterController::slopeLimit
179 \since 6.13
180
181 This property defines the steepest slope, as an angle in degrees, that the
182 character controller can climb. The angle is measured from the plane
183 perpendicular to the character's up direction, so \c 0 only allows
184 flat ground and \c 90 allows any slope.
185
186 Range: \c{[0.0, 90.0]}
187
188 \default 45
189
190 \note The slope limit only applies to slopes on static bodies, such as a
191 \l StaticRigidBody, and not to \l SphereShape or \l CapsuleShape shapes. On a
192 dynamic or kinematic body, or on a sphere or capsule, it has no effect, and
193 neither has \l slideOnSteepSlopes.
194
195 \sa maximumStepHeight
196 \sa slideOnSteepSlopes
197 \sa sliding
198*/
199
200/*!
201 \qmlproperty bool CharacterController::sliding
202 \since 6.13
203
204 This read-only property is \c true while the character is on a slope steeper
205 than \l slopeLimit and \l slideOnSteepSlopes is \c true, so that the character
206 slides down instead of following its movement. It is always \c false when
207 \l slideOnSteepSlopes is \c false.
208
209 Use it to tell the character's animations and input handling that the
210 movement is being limited by the surface.
211
212 \sa slopeLimit
213 \sa slideOnSteepSlopes
214*/
215
216/*!
217 \qmlproperty bool CharacterController::slideOnSteepSlopes
218 \since 6.13
219
220 This property defines whether the character slides down slopes steeper than
221 \l slopeLimit. The character can never climb such a slope; with this
222 property \c false, it stays where it is on one, and with \c true, it slides
223 down, and \l sliding is \c true while it does.
224
225 \default false
226
227 \sa slopeLimit
228 \sa sliding
229*/
230
231/*!
232 \qmlproperty enumeration CharacterController::movementMode
233 \since 6.13
234
235 This property defines how the character controller uses the movement vector.
236
237 \value CharacterController.ForwardBased
238 The character moves relative to its own orientation. Gravity is applied if defined, and
239 \l landed is emitted.
240 \value CharacterController.Free
241 The character uses the movement vector as a global movement vector in the scene. In this mode,
242 gravity, midAirControl, and landed are ignored, though gravity is still used to determine the up
243 direction of the node.
244
245 \default CharacterController.ForwardBased
246
247 \sa gravity
248 \sa movement
249 \sa midAirControl
250 \sa landed
251*/
252
253/*!
254 \qmlsignal CharacterController::landed(real speed)
255 \since 6.13
256
257 This signal is emitted when the character lands after being in the air.
258 The \a speed parameter is how fast, in scene units per second, the character
259 was falling at the moment of impact. It is always positive.
260
261 \note This signal is not emitted when \l movementMode is
262 \c CharacterController.Free. It doesn't need \l enableShapeHitCallback.
263*/
264
265/*!
266 \qmlproperty quaternion CharacterController::gravityOrientation
267 \since 6.13
268
269 This property holds the rotation that turns the scene's up axis, positive y, into
270 the character's current up direction, which is opposite to its gravity. Use it
271 when the direction of gravity changes, such as on a planet, to keep the
272 character upright on the surface.
273
274 The rotation follows changes in the direction of gravity a small step at a time,
275 rather than being calculated from a fixed reference direction. This keeps it free
276 of sudden spins anywhere on a sphere, including at its poles. As a result, the
277 rotation depends on the path the character took, not only on where it is.
278
279 If the gravity is zero, the rotation keeps its last value.
280
281 Combine it with the player's look direction to rotate the character:
282
283 \qml
284 CharacterController {
285 id: playerController
286 property real playerYaw: 0
287
288 rotation: playerController.gravityOrientation
289 .times(Quaternion.fromEulerAngles(0, playerYaw, 0))
290 }
291 \endqml
292
293 \sa gravity
294*/
295
296QCharacterController::QCharacterController() = default;
297
298const QVector3D &QCharacterController::movement() const
299{
300 return m_movement;
301}
302
303void QCharacterController::setMovement(const QVector3D &newMovement)
304{
305 if (!QPhysicsUtils::isFinite(newMovement)) {
306 qWarning() << "CharacterController: movement must be finite, ignoring" << newMovement;
307 return;
308 }
309
310 if (m_movement == newMovement)
311 return;
312 m_movement = newMovement;
313 emit movementChanged();
314}
315
316const QVector3D &QCharacterController::gravity() const
317{
318 return m_gravity;
319}
320
321void QCharacterController::setGravity(const QVector3D &newGravity)
322{
323 if (!QPhysicsUtils::isFinite(newGravity)) {
324 qWarning() << "CharacterController: gravity must be finite, ignoring" << newGravity;
325 return;
326 }
327
328 if (m_gravity == newGravity)
329 return;
330 m_gravity = newGravity;
331 // Zero is how an application stops the character falling, for a ladder or
332 // water, so drop the speed it built up. Leaving a GravityField is not,
333 // and getDisplacement() lets the character coast on after that.
334 if (newGravity.isNull())
335 m_freeFallVelocity = QVector3D(0.0f, 0.0f, 0.0f);
336 emit gravityChanged();
337}
338
339void QCharacterController::addEnvironmentGravity(const QVector3D &gravity)
340{
341 m_environmentGravity += gravity;
342}
343
344void QCharacterController::clearEnvironmentGravity()
345{
346 m_environmentGravity = QVector3D(0.0f, 0.0f, 0.0f);
347}
348
349QVector3D QCharacterController::effectiveGravity() const
350{
351 return m_gravity + m_environmentGravity;
352}
353
354// Calculates character displacement based on movement input and gravity field
355QVector3D QCharacterController::getDisplacement(float deltaTime)
356{
357 if (deltaTime <= 0.0f) {
358 return QVector3D(0.0f, 0.0f, 0.0f);
359 }
360
361 // In Free mode, use the movement vector directly as provided.
362 // Custom movement mechanics and physics are managed externally by the user.
363 if (m_movementMode == MovementMode::Free) {
364 return m_movement * deltaTime;
365 }
366
367 // Transform local movement velocity relative to the character's orientation in the scene
368 const QVector3D moveVelocity = sceneRotation() * m_movement;
369 QVector3D displacement = moveVelocity * deltaTime;
370
371 // This frame's gravity, including what GravityFields contribute
372 const QVector3D g = effectiveGravity();
373 if (g.isNull() && m_freeFallVelocity.isNull()) {
374 return displacement;
375 }
376
377 const bool hasGravity = !g.isNull();
378 const QVector3D gravityDir = hasGravity ? g.normalized() : QVector3D(0.0f, 0.0f, 0.0f);
379
380 // Grounded check: verifies if the character is currently touching the surface below
381 const bool grounded = (m_collisions & Collision::Down);
382
383 // Detect state transitions (leaving ground vs landing)
384 const bool landing = (!m_lastGrounded && grounded);
385
386 m_lastGrounded = grounded;
387
388 // Upon landing, report the speed along the direction of gravity at the
389 // moment of impact. Lateral motion comes from movement input, or from
390 // the launch velocity when mid-air control is off.
391 if (landing) {
392 const QVector3D impactVelocity = m_freeFallVelocity + (m_midAirControl ? moveVelocity : m_jumpVelocity);
393 // Without gravity, a character coasting on the speed it built up under a
394 // GravityField lands along the way it was falling.
395 const QVector3D fallDir = hasGravity ? gravityDir : m_freeFallVelocity.normalized();
396 const float impactSpeed = QVector3D::dotProduct(impactVelocity, fallDir);
397 if (impactSpeed > 0.0f) {
398 const QPointer<QCharacterController> self(this);
399 emit landed(impactSpeed);
400 // A handler for landed can delete the controller.
401 if (!self)
402 return QVector3D(0.0f, 0.0f, 0.0f);
403 }
404 }
405
406 const QVector3D gravityStepDisp = 0.5f * g * deltaTime * deltaTime;
407
408 if (grounded) {
409 // Contact consumes any free-fall velocity built up in the air, and the
410 // surface velocity is recorded so a take-off can lock onto it.
411 m_freeFallVelocity = QVector3D(0.0f, 0.0f, 0.0f);
412 m_jumpVelocity = moveVelocity;
413
414 const bool jump = QVector3D::dotProduct(gravityStepDisp + displacement, gravityDir) < 0.0f
415 && !landing;
416
417 if (m_sliding) {
418 // Slide down a slope too steep to stand on at a constant speed: the
419 // speed a free fall reaches after slideTime seconds. A jump has to
420 // be faster than that to leave the slope.
421 // TODO: Compute the slide speed from the slope angle and the material friction.
422 constexpr float slideTime = 0.7f;
423 return displacement + g * slideTime * deltaTime;
424 }
425
426 if (!jump) {
427 // Keep ground contact on steps and slopes with one frame's worth of
428 // gravity, as when the character starts to fall, so that walking off
429 // a ledge doesn't drop it further than falling would.
430 return displacement + gravityStepDisp;
431 }
432 }
433
434 // If mid-air control is disabled, lock motion strictly to the launch velocity
435 if (!m_midAirControl) {
436 displacement = m_jumpVelocity * deltaTime;
437 }
438
439 // Accumulate gravity over time and apply free-fall velocity to total displacement
440 displacement += m_freeFallVelocity * deltaTime;
441 m_freeFallVelocity += g * deltaTime;
442
443 const bool hitCeiling = (m_collisions & Collision::Up);
444 if (!m_midAirControl && hitCeiling && hasGravity) {
445 // Remove only the velocity component of m_jumpVelocity pointing opposite to gravity
446 const QVector3D upDir = -gravityDir;
447 const float upSpeed = QVector3D::dotProduct(m_jumpVelocity, upDir);
448 if (upSpeed > 0.0f) {
449 m_jumpVelocity -= upDir * upSpeed;
450 }
451 }
452
453 return displacement;
454}
455
456bool QCharacterController::midAirControl() const
457{
458 return m_midAirControl;
459}
460
461void QCharacterController::setMidAirControl(bool newMidAirControl)
462{
463 if (m_midAirControl == newMidAirControl)
464 return;
465 m_midAirControl = newMidAirControl;
466 emit midAirControlChanged();
467}
468
469void QCharacterController::teleport(const QVector3D &position)
470{
471 if (!QPhysicsUtils::isFinite(position)) {
472 qWarning() << "CharacterController: teleport() position must be finite, ignoring"
473 << position;
474 return;
475 }
476
477 m_teleport = true;
478 m_teleportPosition = position;
479 m_freeFallVelocity = {};
480}
481
482bool QCharacterController::getTeleport(QVector3D &position)
483{
484 if (m_teleport) {
485 position = m_teleportPosition;
486 m_teleport = false;
487 return true;
488 }
489 return false;
490}
491
492const QCharacterController::Collisions &QCharacterController::collisions() const
493{
494 return m_collisions;
495}
496
497void QCharacterController::setCollisions(const Collisions &newCollisions)
498{
499 if (m_collisions == newCollisions)
500 return;
501 m_collisions = newCollisions;
502 emit collisionsChanged();
503}
504
505bool QCharacterController::enableShapeHitCallback() const
506{
507 return m_enableShapeHitCallback;
508}
509
510QAbstractPhysXNode *QCharacterController::createPhysXBackend()
511{
512 return new QPhysXCharacterController(this);
513}
514
515void QCharacterController::setEnableShapeHitCallback(bool newEnableShapeHitCallback)
516{
517 if (m_enableShapeHitCallback == newEnableShapeHitCallback)
518 return;
519 m_enableShapeHitCallback = newEnableShapeHitCallback;
520 emit enableShapeHitCallbackChanged();
521}
522
523float QCharacterController::maximumStepHeight() const
524{
525 return m_maximumStepHeight;
526}
527
528void QCharacterController::setMaximumStepHeight(float newMaximumStepHeight)
529{
530 if (!qIsFinite(newMaximumStepHeight)) {
531 qWarning() << "CharacterController: maximumStepHeight must be finite, ignoring"
532 << newMaximumStepHeight;
533 return;
534 }
535
536 if (newMaximumStepHeight < 0.f)
537 newMaximumStepHeight = -1.f;
538
539 if (qFuzzyCompare(m_maximumStepHeight, newMaximumStepHeight))
540 return;
541
542 m_maximumStepHeight = newMaximumStepHeight;
543 emit maximumStepHeightChanged();
544}
545
546float QCharacterController::slopeLimit() const
547{
548 return m_slopeLimit;
549}
550
551void QCharacterController::setSlopeLimit(float newSlopeLimit)
552{
553 if (!qIsFinite(newSlopeLimit)) {
554 qWarning() << "CharacterController: slopeLimit must be finite, ignoring"
555 << newSlopeLimit;
556 return;
557 }
558
559 newSlopeLimit = qBound(0.f, newSlopeLimit, 90.f);
560
561 if (qFuzzyCompare(m_slopeLimit, newSlopeLimit))
562 return;
563 m_slopeLimit = newSlopeLimit;
564 emit slopeLimitChanged();
565}
566
567bool QCharacterController::slideOnSteepSlopes() const
568{
569 return m_slideOnSteepSlopes;
570}
571
572void QCharacterController::setSlideOnSteepSlopes(bool newSlideOnSteepSlopes)
573{
574 if (m_slideOnSteepSlopes == newSlideOnSteepSlopes)
575 return;
576 m_slideOnSteepSlopes = newSlideOnSteepSlopes;
577 emit slideOnSteepSlopesChanged();
578}
579
580QCharacterController::MovementMode QCharacterController::movementMode() const
581{
582 return m_movementMode;
583}
584
585void QCharacterController::setMovementMode(MovementMode newMovementMode)
586{
587 if (m_movementMode == newMovementMode)
588 return;
589 m_movementMode = newMovementMode;
590 emit movementModeChanged();
591}
592
593QQuaternion QCharacterController::gravityOrientation() const
594{
595 return m_gravityOrientation;
596}
597
598bool QCharacterController::isSliding() const
599{
600 return m_sliding;
601}
602
603void QCharacterController::setSliding(bool sliding)
604{
605 if (m_sliding == sliding)
606 return;
607 m_sliding = sliding;
608 emit slidingChanged();
609}
610
611void QCharacterController::setGravityOrientation(const QQuaternion &newRotation)
612{
613 if (m_gravityOrientation != newRotation) {
614 m_gravityOrientation = newRotation;
615 emit gravityOrientationChanged();
616 }
617}
618
#define QT_BEGIN_NAMESPACE
#define QT_END_NAMESPACE