ezEngine  Release 25.03
ezJoltDefaultCharacterComponent Class Reference

An example character controller (CC) implementation build upon ezJoltCharacterControllerComponent. More...

#include <JoltDefaultCharacterComponent.h>

Inheritance diagram for ezJoltDefaultCharacterComponent:

Classes

struct  Config
 

Public Types

enum  GroundState : ezUInt8 { GroundState::OnGround, GroundState::Sliding, GroundState::InAir }
 

Public Member Functions

virtual void SerializeComponent (ezWorldWriter &inout_stream) const override
 Override this to save the current state of the component to the given stream.
 
virtual void DeserializeComponent (ezWorldReader &inout_stream) override
 Override this to load the current state of the component from the given stream. More...
 
void SetWalkSurfaceInteraction (const char *szName)
 
const char * GetWalkSurfaceInteraction () const
 
void SetFallbackWalkSurfaceFile (ezStringView sFile)
 
ezStringView GetFallbackWalkSurfaceFile () const
 
void SetHeadObjectReference (const char *szReference)
 Sets an object GUID for an object that is the 'head' (controls the camera).
 
void SetInputState (ezMsgMoveCharacterController &ref_msg)
 This message is used to steer the CC.
 
float GetCurrentCapsuleHeight () const
 Returns the current height of the entire capsule (crouching or standing).
 
float GetCurrentCylinderHeight () const
 Returns the current height of the cylindrical part of the capsule (crouching or standing).
 
virtual float GetShapeRadius () const override
 Returns the radius of the shape. This never changes at runtime.
 
GroundState GetGroundState () const
 
bool IsStandingOnGround () const
 
bool IsSlidingOnGround () const
 
bool IsInAir () const
 
bool IsCrouching () const
 
void TeleportCharacter (const ezVec3 &vGlobalFootPosition)
 Instantly teleports the character to the target position. Doesn't change its rotation.
 
- Public Member Functions inherited from ezJoltCharacterControllerComponent
void SetObjectToIgnore (ezUInt32 uiObjectFilterID)
 The CC will move through the given physics body. More...
 
void ClearObjectToIgnore ()
 
void SetMaxClimbingSlope (ezAngle slope)
 The maximum slope that the character can walk up.
 
ezAngle GetMaxClimbingSlope () const
 
void SetMass (float fMass)
 The mass with which the character will push down on objects that it is standing on.
 
float GetMass () const
 
void SetStrength (float fStrength)
 The strength with which the character will push against objects that it is running into.
 
float GetStrength () const
 
- Public Member Functions inherited from ezComponent
void SetActiveFlag (bool bEnabled)
 Sets the active flag of the component, which affects its active state. More...
 
bool GetActiveFlag () const
 Checks whether the 'active flag' is set on this component. Note that this does not mean that the component is also 'active'. More...
 
bool IsActive () const
 Checks whether this component is in an active state. More...
 
bool IsActiveAndInitialized () const
 Returns whether this component is active and initialized. More...
 
bool IsActiveAndSimulating () const
 Whether the component is currently active and simulation has been started as well. More...
 
ezComponentManagerBaseGetOwningManager ()
 Returns the corresponding manager for this component.
 
const ezComponentManagerBaseGetOwningManager () const
 Returns the corresponding manager for this component.
 
ezGameObjectGetOwner ()
 Returns the owner game object if the component is attached to one or nullptr.
 
const ezGameObjectGetOwner () const
 Returns the owner game object if the component is attached to one or nullptr.
 
ezWorldGetWorld ()
 Returns the corresponding world for this component.
 
const ezWorldGetWorld () const
 Returns the corresponding world for this component.
 
ezComponentHandle GetHandle () const
 Returns a handle to this component.
 
ezUInt32 GetUniqueID () const
 Returns the unique id for this component.
 
void SetUniqueID (ezUInt32 uiUniqueID)
 Sets the unique id for this component.
 
void EnsureInitialized ()
 Ensures that the component is initialized. Must only be called from another component's Initialize callback.
 
void EnsureSimulationStarted ()
 Ensures that the OnSimulationStarted method has been called. Must only be called from another component's OnSimulationStarted callback.
 
EZ_ALWAYS_INLINE bool SendMessage (ezMessage &ref_msg)
 Sends a message to this component.
 
EZ_ALWAYS_INLINE bool SendMessage (ezMessage &ref_msg) const
 
void PostMessage (const ezMessage &msg, ezTime delay=ezTime::MakeZero(), ezObjectMsgQueueType::Enum queueType=ezObjectMsgQueueType::NextFrame) const
 Queues the message for the given phase. The message is processed after the given delay in the corresponding phase.
 
virtual bool HandlesMessage (const ezMessage &msg) const
 Returns whether the given Message is handled by this component.
 
void SetUserFlag (ezUInt8 uiFlagIndex, bool bSet)
 Be careful to check which flags may already be in use by base classes.
 
bool GetUserFlag (ezUInt8 uiFlagIndex) const
 Retrieves a custom flag. Index must be between 0 and 7.
 
void SetCreatedByPrefab ()
 Adds ezObjectFlags::CreatedByPrefab to the component. See the flag for details.
 
bool WasCreatedByPrefab () const
 Checks whether the ezObjectFlags::CreatedByPrefab flag is set on this component.
 
- Public Member Functions inherited from ezReflectedClass
virtual const ezRTTIGetDynamicRTTI () const
 
bool IsInstanceOf (const ezRTTI *pType) const
 Returns whether the type of this instance is of the given type or derived from it.
 
template<typename T >
EZ_ALWAYS_INLINE bool IsInstanceOf () const
 Returns whether the type of this instance is of the given type or derived from it.
 

Public Attributes

ezAngle m_RotateSpeed = ezAngle::MakeFromDegree(90.0f)
 How many degrees per second the character turns.
 
float m_fShapeRadius = 0.25f
 The radius of the capsule shape.
 
float m_fCylinderHeightCrouch = 0.9f
 The total cylinder height when the character crouches.
 
float m_fCylinderHeightStand = 1.7f
 The total cylinder height when the character stands.
 
float m_fFootRadius = 0.15f
 The radius of the feet area, where it is checked whether the CC properly stands on the ground.
 
float m_fWalkSpeedCrouching = 0.5f
 Meters per second movement speed when crouching.
 
float m_fWalkSpeedStanding = 1.5f
 Meters per second movement speed when standing.
 
float m_fWalkSpeedRunning = 3.5f
 Meters per second movement speed when standing and running.
 
float m_fMaxStepUp = 0.25f
 The maximum step height that the CC can step up in a single frame.
 
float m_fMaxStepDown = 0.25f
 The maximum step height that the CC can step down in a single frame (without 'falling').
 
float m_fJumpImpulse = 5.0f
 The physics impulse to use for jumping.
 
ezHashedString m_sWalkSurfaceInteraction
 The surface interaction to spawn regularly when walking.
 
ezSurfaceResourceHandle m_hFallbackWalkSurface
 The surface type to use for interactions, when no other surface type is available.
 
float m_fWalkInteractionDistance = 1.0f
 How far the CC has to walk for spawning another surface interaction.
 
float m_fRunInteractionDistance = 3.0f
 How far the CC has to run for spawning another surface interaction.
 
float m_fAirSpeed = 2.5f
 How fast to move while falling. The higher, the more "air control" the player has.
 
float m_fAirFriction = 0.5f
 How much lateral motion to lose while falling.
 
- Public Attributes inherited from ezJoltCharacterControllerComponent
ezUInt8 m_uiCollisionLayer = 0
 The collision layer determines with which other actors this actor collides. More...
 
ezUInt8 m_uiPresenceCollisionLayer = 0
 In case a 'presence shape' is used, this defines which geometry the presence bodies collides with.
 
ezBitflags< ezJoltCharacterDebugFlags > m_DebugFlags
 What aspects of the CC to visualize.
 

Protected Member Functions

virtual void OnSimulationStarted () override
 This method is called once for active components, at the start of the next world update, but only when the world is simulated. More...
 
virtual void OnActivated () override
 This method is called when the component gets activated. More...
 
virtual void OnDeactivated () override
 This method is called when the component gets deactivated. More...
 
void OnUpdateLocalBounds (ezMsgUpdateLocalBounds &msg) const
 
virtual void OnApplyRootMotion (ezMsgApplyRootMotion &msg)
 
virtual void DetermineConfig (Config &out_inputs)
 
virtual void UpdateCharacter () override
 Called up to once per frame, but potentially less often, if physics updates were skipped due to high framerates. More...
 
virtual void ApplyRotationZ ()
 
void ResetInputState ()
 Clears the input states to neutral values.
 
void ResetInternalState ()
 
virtual JPH::Ref< JPH::Shape > MakeNextCharacterShape () override
 Creates a new shape with the given height (and fixed radius)
 
void ApplyCrouchState ()
 
void InteractWithSurfaces (const ContactPoint &contact, const Config &cfg)
 
void StoreLateralVelocity ()
 
void ClampLateralVelocity ()
 
void MoveHeadObject ()
 
void DebugVisualizations ()
 
void CheckFeet ()
 
- Protected Member Functions inherited from ezJoltCharacterControllerComponent
EZ_ALWAYS_INLINE float GetUpdateTimeDelta () const
 Returns the time delta to use for updating the character. This may differ from the world delta.
 
EZ_ALWAYS_INLINE float GetInverseUpdateTimeDelta () const
 Returns the inverse of update time delta.
 
JPH::CharacterVirtual * GetJoltCharacter ()
 Gives access to the internally used JPH::CharacterVirtual.
 
const JPH::CharacterVirtual * GetJoltCharacter () const
 
ezResult TryChangeShape (JPH::Shape *pNewShape)
 Attempts to change the character shape to the new one. Fails if the new shape overlaps with surrounding geometry.
 
void RawMoveWithVelocity (const ezVec3 &vVelocity, float fMaxStairStepUp, float fMaxStepDown)
 Moves the character using the given velocity and timestep, making it collide with and slide along obstacles.
 
void RawMoveIntoDirection (const ezVec3 &vDirection)
 Variant of RawMoveWithVelocity() that takes a direction vector instead.
 
void RawMoveToPosition (const ezVec3 &vTargetPosition)
 Variant of RawMoveWithVelocity() that takes a target position instead.
 
void TeleportToPosition (const ezVec3 &vGlobalFootPos)
 Teleports the character to the destination position, even if it would get stuck there.
 
bool StickToGround (float fMaxDist)
 If the CC is slightly above the ground, this will move it down so that it touches the ground. More...
 
void CollectCastContacts (ezDynamicArray< ContactPoint > &out_Contacts, const JPH::Shape *pShape, const ezVec3 &vQueryPosition, const ezQuat &qQueryRotation, const ezVec3 &vSweepDir) const
 Gathers all contact points that are found by sweeping the shape along a direction.
 
void CollectContacts (ezDynamicArray< ContactPoint > &out_Contacts, const JPH::Shape *pShape, const ezVec3 &vQueryPosition, const ezQuat &qQueryRotation, float fCollisionTolerance) const
 Gathers all contact points of the shape at the target position. More...
 
ezVec3 GetContactVelocityAndPushAway (const ContactPoint &contact, float fPushForce)
 Detects the velocity at the contact point. If it is a dynamic body, a force pushing it away is applied. More...
 
void SpawnContactInteraction (const ContactPoint &contact, const ezHashedString &sSurfaceInteraction, ezSurfaceResourceHandle hFallbackSurface, const ezVec3 &vInteractionNormal=ezVec3(0, 0, 1))
 Spawns a surface interaction prefab at the given contact point. More...
 
void VisualizeContact (const ContactPoint &contact, const ezColor &color) const
 Debug draws the contact point.
 
void VisualizeContacts (const ezDynamicArray< ContactPoint > &contacts, const ezColor &color) const
 Debug draws all the contact points.
 
- Protected Member Functions inherited from ezComponent
 ezComponent ()
 Keep the constructor private or protected in derived classes, so it cannot be called manually.
 
bool IsDynamic () const
 Returns whether this component is dynamic and thus can only be attached to dynamic game objects.
 
virtual ezWorldModuleTypeId GetTypeId () const =0
 
virtual ezComponentMode::Enum GetMode () const =0
 
virtual void Initialize ()
 Can be overridden for basic initialization that depends on a valid hierarchy and position. More...
 
virtual void Deinitialize ()
 This method is called before the component is destroyed. A derived type can override this method to do common de-initialization work. More...
 
void EnableUnhandledMessageHandler (bool enable)
 By default disabled. Enable to have OnUnhandledMessage() called for every unhandled message.
 
virtual bool OnUnhandledMessage (ezMessage &msg, bool bWasPostedMsg)
 When EnableUnhandledMessageHandler() was activated, this is called for all messages for which there is no dedicated message handler. More...
 
virtual bool OnUnhandledMessage (ezMessage &msg, bool bWasPostedMsg) const
 When EnableUnhandledMessageHandler() was activated, this is called for all messages for which there is no dedicated message handler. More...
 
bool IsInitialized () const
 
bool IsInitializing () const
 
bool IsSimulationStarted () const
 

Protected Attributes

GroundState m_LastGroundState = GroundState::InAir
 
ezUInt8 m_uiInputJumpBit: 1
 
ezUInt8 m_uiInputCrouchBit: 1
 
ezUInt8 m_uiInputRunBit: 1
 
ezUInt8 m_uiIsCrouchingBit: 1
 
ezAngle m_InputRotateZ
 
ezVec2 m_vInputDirection = ezVec2::MakeZero()
 
float m_fVelocityUp = 0.0f
 
float m_fNextCylinderHeight = 0
 
float m_fAccumulatedWalkDistance = 0.0f
 
ezVec2 m_vVelocityLateral = ezVec2::MakeZero()
 
ezTransform m_PreviousTransform
 
bool m_bFeetOnSolidGround = false
 
float m_fCurrentCylinderHeight = 0
 
float m_fHeadHeightOffset = 0.0f
 
float m_fHeadTargetHeight = 0.0f
 
ezGameObjectHandle m_hHeadObject
 
ezVec3 m_vAbsoluteRootMotion = ezVec3::MakeZero()
 
ezUInt32 m_uiUserDataIndex = ezInvalidIndex
 
ezUInt32 m_uiJoltBodyID = ezInvalidIndex
 
- Protected Attributes inherited from ezComponent
const ezRTTIm_pMessageDispatchType = nullptr
 Messages will be dispatched to this type. Default is what GetDynamicRTTI() returns, can be redirected if necessary.
 

Additional Inherited Members

- Static Public Member Functions inherited from ezNoBase
static const ezRTTIGetStaticRTTI ()
 

Detailed Description

An example character controller (CC) implementation build upon ezJoltCharacterControllerComponent.

This component implements typical behavior for an FPS type of game. It is mainly meant as an example, as most games would rather implement their own CC to control the exact details.

It is also possible to derive from this component and override some virtual functions to just tweak the behavior of this sample implementation, in case you only need minor tweaks.

Member Enumeration Documentation

◆ GroundState

Enumerator
OnGround 

Character is touching the ground.

Sliding 

Character is touching a steep surface and therefore slides downwards.

InAir 

Character isn't touching any ground surface (may still touch a wall or ceiling)

Member Function Documentation

◆ DeserializeComponent()

void ezJoltDefaultCharacterComponent::DeserializeComponent ( ezWorldReader inout_stream)
overridevirtual

Override this to load the current state of the component from the given stream.

The active state will be automatically serialized. The 'initialized' state is not serialized, all components will be initialized after creation, even if they were already in an initialized state when they were serialized.

Reimplemented from ezJoltCharacterControllerComponent.

◆ OnActivated()

void ezJoltDefaultCharacterComponent::OnActivated ( )
overrideprotectedvirtual

This method is called when the component gets activated.

By default a component is active, but it can be created in an inactive state. In such a case OnActivated() is only called once a component is activated. If a component gets switched between active and inactive at runtime, OnActivated() and OnDeactivated() are called accordingly. In contrast Initialize() and Deinitialize() are only ever called once.

See also
OnActivated(), OnDeactivated(), Initialize(), Deinitialize(), OnSimulationStarted()

Reimplemented from ezComponent.

◆ OnDeactivated()

void ezJoltDefaultCharacterComponent::OnDeactivated ( )
overrideprotectedvirtual

This method is called when the component gets deactivated.

Upon destruction, a component that is active first gets deactivated. Therefore OnDeactivated() should be used for typical game code cleanup.

See also
OnActivated(), OnDeactivated(), Initialize(), Deinitialize(), OnSimulationStarted()

Reimplemented from ezJoltCharacterControllerComponent.

◆ OnSimulationStarted()

void ezJoltDefaultCharacterComponent::OnSimulationStarted ( )
overrideprotectedvirtual

This method is called once for active components, at the start of the next world update, but only when the world is simulated.

This is the one preferred method to setup typical game logic. In a pure game environment there is no practical difference between OnActivated() and OnSimulationStarted(), as OnSimulationStarted() will be called right after OnActivated().

However, when a scene is open inside the editor, there is an important difference: OnActivated() is called once the component was created. OnSimulationStarted() is only called once the game simulation is started inside the editor. As an example, if a component starts a sound in OnActivated(), that sound will play right after the scene has been loaded into the editor. If instead the sound gets started in OnSimulationStarted(), it will only play once the user starts the game mode inside the editor.

Additionally, OnSimulationStarted() is only executed once, even if the ezWorld pauses and resumes world simulation multiple times. However, note that it will be called again after the component has been deactivated and is activated again.

See also
OnActivated(), OnDeactivated(), Initialize(), Deinitialize(), OnSimulationStarted()

Reimplemented from ezJoltCharacterControllerComponent.

◆ UpdateCharacter()

void ezJoltDefaultCharacterComponent::UpdateCharacter ( )
overrideprotectedvirtual

Called up to once per frame, but potentially less often, if physics updates were skipped due to high framerates.

All shape modifications and moves should only be executed during this step. The given deltaTime should be used, rather than the world's time diff.

Implements ezJoltCharacterControllerComponent.


The documentation for this class was generated from the following files: