Class KCCController
Kinematic Character Controller wrapper that implements KinematicCharacterController.ICharacterController. Handles movement, jumping, crouching, sprinting, and state transitions.
public class KCCController : MonoBehaviour, ICharacterController
- Inheritance
-
ObjectComponentBehaviourMonoBehaviourKCCController
- Implements
-
ICharacterController
- Inherited Members
-
MonoBehaviour.IsInvoking()MonoBehaviour.CancelInvoke()MonoBehaviour.StopCoroutine(Coroutine)MonoBehaviour.StopAllCoroutines()MonoBehaviour.destroyCancellationTokenMonoBehaviour.useGUILayoutMonoBehaviour.didStartMonoBehaviour.didAwakeMonoBehaviour.runInEditModeBehaviour.enabledBehaviour.isActiveAndEnabledComponent.GetComponent<T>()Component.TryGetComponent<T>(out T)Component.GetComponentInChildren<T>()Component.GetComponentsInChildren<T>()Component.GetComponentInParent<T>()Component.GetComponentsInParent<T>()Component.GetComponents<T>()Component.GetComponentIndex()Component.CompareTag(TagHandle)Component.transformComponent.transformHandleComponent.gameObjectComponent.tagObject.GetEntityId()Object.MemberwiseClone()Object.GetInstanceID()Object.GetHashCode()Object.InstantiateAsync<T>(T)Object.InstantiateAsync<T>(T, Transform)Object.InstantiateAsync<T>(T, Vector3, Quaternion)Object.InstantiateAsync<T>(T, Transform, Vector3, Quaternion)Object.Instantiate(Object, Vector3, Quaternion)Object.Instantiate(Object, Vector3, Quaternion, Transform)Object.Instantiate(Object)Object.Instantiate(Object, Scene)Object.Instantiate<T>(T, InstantiateParameters)Object.Instantiate<T>(T, Vector3, Quaternion, InstantiateParameters)Object.Instantiate(Object, Transform)Object.Instantiate<T>(T)Object.Instantiate<T>(T, Vector3, Quaternion)Object.Instantiate<T>(T, Vector3, Quaternion, Transform)Object.Instantiate<T>(T, Transform)Object.Destroy(Object)Object.DestroyImmediate(Object)Object.DontDestroyOnLoad(Object)Object.DestroyObject(Object)Object.FindObjectsOfType<T>()Object.FindObjectsByType<T>(FindObjectsSortMode)Object.FindObjectsByType<T>(FindObjectsInactive, FindObjectsSortMode)Object.FindObjectOfType<T>()Object.FindFirstObjectByType<T>()Object.FindAnyObjectByType<T>()Object.FindFirstObjectByType<T>(FindObjectsInactive)Object.FindAnyObjectByType<T>(FindObjectsInactive)Object.FindObjectsByType<T>()Object.FindObjectsByType<T>(FindObjectsInactive)Object.ToString()Object.nameObject.hideFlags
Fields
AirAccelerationSpeed
Acceleration applied to air movement.
public float AirAccelerationSpeed
Field Value
AllowJumpingWhenSliding
[Header("Jumping")]
public bool AllowJumpingWhenSliding
Field Value
BonusOrientationMethod
Additional orientation method for adjusting the character up vector.
public BonusOrientationMethod BonusOrientationMethod
Field Value
BonusOrientationSharpness
Sharpness for bonus orientation smoothing.
public float BonusOrientationSharpness
Field Value
CameraFollowPoint
Transform that the camera follows and orbits around.
public Transform CameraFollowPoint
Field Value
- Transform
CanClimb
[Header("Climbing")]
public bool CanClimb
Field Value
CanSwim
[Header("Swimming")]
public bool CanSwim
Field Value
CapsuleBaseOffset
Base offset of the capsule from the character pivot.
public float CapsuleBaseOffset
Field Value
Character
The player character this controller belongs to.
public IPlayerCharacter Character
Field Value
ClimbSpeedTemplate
Optional: a character attribute that scales climbing speed. Without one, climbing follows Move Speed alone, so whatever slows a character's walk slows its climb too.
public CharacterAttributeTemplate ClimbSpeedTemplate
Field Value
ClimbTurnSharpness
How quickly a climber turns to face the climbable (and the way off it over the top).
public float ClimbTurnSharpness
Field Value
CrouchedCapsuleHeight
Capsule height when crouching.
public float CrouchedCapsuleHeight
Field Value
Drag
Air drag coefficient applied to velocity.
public float Drag
Field Value
FastFallSpeedTemplate
Template for the character attribute that modifies fast fall speed.
public CharacterAttributeTemplate FastFallSpeedTemplate
Field Value
FlySharpness
How quickly a flyer's velocity follows what it is asked for.
public float FlySharpness
Field Value
FlySpeed
Flying speed, metres per second; sprint multiplies it by FlySprintMultiplier.
public float FlySpeed
Field Value
FlySprintMultiplier
Sprinting while flying multiplies the speed by this.
public float FlySprintMultiplier
Field Value
FullCapsuleHeight
Capsule height when standing.
public float FullCapsuleHeight
Field Value
GravityTemplate
Template for the character attribute that modifies gravity.
public CharacterAttributeTemplate GravityTemplate
Field Value
IgnoredColliders
[Header("Misc")]
public List<Collider> IgnoredColliders
Field Value
- List<Collider>
JumpPostGroundingGraceTime
Grace period after leaving ground during which a jump is still allowed.
public float JumpPostGroundingGraceTime
Field Value
JumpPreGroundingGraceTime
Grace period before landing during which a jump request is still accepted.
public float JumpPreGroundingGraceTime
Field Value
JumpScalableForwardSpeed
Forward speed added to velocity when jumping.
public float JumpScalableForwardSpeed
Field Value
JumpSpeedTemplate
Template for the character attribute that modifies jump speed.
public CharacterAttributeTemplate JumpSpeedTemplate
Field Value
LavaSwimSpeedShare
The share of the swimming speed left in lava, which is thick.
public float LavaSwimSpeedShare
Field Value
MaxAirMoveSpeed
[Header("Air Movement")]
public float MaxAirMoveSpeed
Field Value
MeshRoot
Root transform of the character mesh for visual scaling (e.g., crouch).
public Transform MeshRoot
Field Value
- Transform
Motor
The kinematic character motor driving movement and collision.
public KinematicCharacterMotor Motor
Field Value
- KinematicCharacterMotor
MoveSpeedTemplate
Template for the character attribute that modifies movement speed.
public CharacterAttributeTemplate MoveSpeedTemplate
Field Value
OrientationMethod
Method used to determine character facing direction.
public OrientationMethod OrientationMethod
Field Value
OrientationSharpness
Sharpness for character rotation smoothing.
public float OrientationSharpness
Field Value
SettleDegrees
Largest angle, in degrees, between the rotation and the upright heading it is turning to that counts as arrived. Below Quaternion.Angle's own resolution (about 0.1 degrees), so the last step of a turn is invisible.
public const float SettleDegrees = 0.05
Field Value
SettleSpeed
Speed, in metres per second, below which a character slowing to a stop has stopped.
public const float SettleSpeed = 0.0001
Field Value
SprintSpeedTemplate
Template for the character attribute that modifies sprint speed.
public CharacterAttributeTemplate SprintSpeedTemplate
Field Value
StableMovementSharpness
[Header("Stable Movement")]
public float StableMovementSharpness
Field Value
SwimBuoyancy
How hard a swimmer near the surface is pulled to its float line, metres per second per metre off it.
public float SwimBuoyancy
Field Value
SwimSharpness
How quickly a swimmer's velocity follows what it is asked for: water is thick, so far softer than the ground's.
public float SwimSharpness
Field Value
SwimSpeedTemplate
Template for the character attribute that modifies swim speed.
public CharacterAttributeTemplate SwimSpeedTemplate
Field Value
Properties
Climb
The climb: which of the scene's climbables, and where in it (Free when not climbing).
public ClimbState Climb { get; }
Property Value
CurrentCharacterState
The current state of the character state machine.
public KCCCharacterState CurrentCharacterState { get; }
Property Value
HasMotion
True while an ability rush (BeginMotion(Vector3, float, float, float)) is driving the character.
public bool HasMotion { get; }
Property Value
HeadDepth
How far under the surface the top of the character's head is, metres; negative while it is out of the water.
public float HeadDepth { get; }
Property Value
IsClimbing
Whether the character is on a ladder, rope ladder or rope now (stepping on or off at its top included).
public bool IsClimbing { get; }
Property Value
IsCrouching
In the crouched stance (the shorter capsule).
public bool IsCrouching { get; }
Property Value
IsFlying
Whether the character is in game-master flight now (/gm fly): no gravity, ground or collisions.
public bool IsFlying { get; }
Property Value
IsSwimming
Whether the character is swimming now.
public bool IsSwimming { get; }
Property Value
VirtualCameraPosition
Position of the virtual camera used for input-relative movement calculations.
public Vector3 VirtualCameraPosition { get; }
Property Value
- Vector3
VirtualCameraRotation
Rotation of the virtual camera used for input-relative movement calculations.
public Quaternion VirtualCameraRotation { get; }
Property Value
- Quaternion
Water
The water over the character this tick (Dry when there is none).
public WaterSample Water { get; }
Property Value
WaterTick
The synced server tick the water is read at (the tide moves the sea): set by the replicate before each motor update. Never the replicate's own tick, which is the owner's unsynchronised counter.
public uint WaterTick { get; set; }
Property Value
Methods
AfterCharacterUpdate(float)
(Called by KinematicCharacterMotor during its update cycle) This is called after the character has finished its movement update
public void AfterCharacterUpdate(float deltaTime)
Parameters
deltaTimefloat
ApplyState(KinematicCharacterMotorState)
Applies a saved motor state to restore the character pose (used during reconcile).
public void ApplyState(KinematicCharacterMotorState state)
Parameters
stateKinematicCharacterMotorStateThe motor state to apply.
BeforeCharacterUpdate(float)
(Called by KinematicCharacterMotor during its update cycle) This is called before the character begins its movement update
public void BeforeCharacterUpdate(float deltaTime)
Parameters
deltaTimefloat
BeginMotion(Vector3, float, float, float)
Starts an ability rush: for durationSeconds the character is driven across the ground along
direction fast enough to cover distance, facing it, whatever its input says.
public bool BeginMotion(Vector3 direction, float distance, float durationSeconds, float tickDelta)
Parameters
directionVector3The way to rush; only its horizontal part is used.
distancefloatHow far, metres.
durationSecondsfloatOver how long.
tickDeltafloatSeconds per network tick.
Returns
- bool
True when the rush started.
Remarks
Predicted. Called from the ability step, which runs after this character's movement step in the same tick,
on the server and on the owner alike (and again on a replayed tick: the ability re-applies it). The rush is then
motor state, reconciled through MotionTicks/MotionSpeed/MotionYaw, so a correction from inside
it continues it rather than dropping it.
Speed and heading are quantised here (centimetres per second; 1/65536 of a turn), so the values both peers drive are the values the wire carries. A rush ends early when something stops it (FishMMO.Shared.KCCController.TickMotion()), and never starts while climbing, swimming or flying.
EndMotion()
Ends an ability rush now, from inside the movement step (stunned, rooted): a replay reaches it by itself.
public void EndMotion()
EndMotionFromHit()
Ends an ability rush because a hit stopped it: from OUTSIDE the movement step, where the ability object resolves its hits.
public void EndMotionFromHit()
Remarks
On the owner the stop is remembered, against the movement tick it followed. A hit is not run again when the owner replays a correction, so a correction from before the hit used to replay the rush straight past the target, and the server's own stop then snapped the charger back to it a moment later. The remembered stop is applied again when a replay passes its tick (ReapplyPredictedRushStop(uint)) or when a correction lands past it with the server still rushing (OnReconciled(uint)), and forgotten once the server's state shows the rush stopped there (or after ExpiryTicks, when the server never struck: then the server's rush is the truth).
On the server it is simply the stop; the reconcile carries it.
GetState()
Captures the current motor and controller state for reconciliation.
public KinematicCharacterMotorState GetState()
Returns
- KinematicCharacterMotorState
A snapshot of the current kinematic state.
IsColliderValidForCollisions(Collider)
Determines if a collider is valid for collision checks, ignoring those in the IgnoredColliders list.
public bool IsColliderValidForCollisions(Collider coll)
Parameters
collColliderCollider to check.
Returns
- bool
True if valid for collision, false if ignored.
MotionDirectionOf(ushort)
The unit horizontal heading a quantised yaw names.
public static Vector3 MotionDirectionOf(ushort yaw)
Parameters
yawushort
Returns
- Vector3
NoteSimulatedTick(uint, bool)
Called after every movement step (first pass and replay) with its tick. recordsStops is true on
the owner only, which is the one peer that replays and so the one that must remember hit stops.
public void NoteSimulatedTick(uint tick, bool recordsStops)
Parameters
OnDiscreteCollisionDetected(Collider)
Called when a discrete collision is detected. Can be used for collision effects.
public void OnDiscreteCollisionDetected(Collider hitCollider)
Parameters
hitColliderColliderCollider hit.
OnGroundHit(Collider, Vector3, Vector3, ref HitStabilityReport)
Called when the character hits the ground. Can be used for landing effects or stability checks.
public void OnGroundHit(Collider hitCollider, Vector3 hitNormal, Vector3 hitPoint, ref HitStabilityReport hitStabilityReport)
Parameters
hitColliderColliderCollider hit.
hitNormalVector3Normal of the hit surface.
hitPointVector3Point of contact.
hitStabilityReportHitStabilityReportStability report for the hit.
OnLanded()
Called when the character lands on stable ground.
protected void OnLanded()
Remarks
Empty, and deliberately so — the extension point is the point, exactly as with
OnLeaveStableGround(). Anything added here runs on every replayed tick of a
reconcile as well as on the live one, so it must be either idempotent or reconciled; see
the note where IsJumping was removed.
OnLeaveStableGround()
Called when the character leaves stable ground. Can be used for airborne effects.
protected void OnLeaveStableGround()
OnMovementHit(Collider, Vector3, Vector3, ref HitStabilityReport)
Called when the character hits something during movement. Can be used for collision effects.
public void OnMovementHit(Collider hitCollider, Vector3 hitNormal, Vector3 hitPoint, ref HitStabilityReport hitStabilityReport)
Parameters
hitColliderColliderCollider hit.
hitNormalVector3Normal of the hit surface.
hitPointVector3Point of contact.
hitStabilityReportHitStabilityReportStability report for the hit.
OnReconciled(uint)
After a correction for reconciledTick has been applied (before the replay): forgets the stops the
server has confirmed or never made, and keeps a stop the correction would undo (the server, a tick or two behind
the owner's hit, still rushing at a tick past it).
public void OnReconciled(uint reconciledTick)
Parameters
reconciledTickuint
OnStateEnter(KCCCharacterState, KCCCharacterState)
Event when entering a state
public void OnStateEnter(KCCCharacterState state, KCCCharacterState fromState)
Parameters
stateKCCCharacterStatefromStateKCCCharacterState
OnStateExit(KCCCharacterState, KCCCharacterState)
Event when exiting a state
public void OnStateExit(KCCCharacterState state, KCCCharacterState toState)
Parameters
stateKCCCharacterStatetoStateKCCCharacterState
PostGroundingUpdate(float)
Called after grounding update to handle landing and leaving ground events. Triggers OnLanded or OnLeaveStableGround as appropriate.
public void PostGroundingUpdate(float deltaTime)
Parameters
deltaTimefloatFrame time.
ProcessHitStabilityReport(Collider, Vector3, Vector3, Vector3, Quaternion, ref HitStabilityReport)
Processes the hit stability report for advanced collision and grounding logic.
public void ProcessHitStabilityReport(Collider hitCollider, Vector3 hitNormal, Vector3 hitPoint, Vector3 atCharacterPosition, Quaternion atCharacterRotation, ref HitStabilityReport hitStabilityReport)
Parameters
hitColliderColliderCollider hit.
hitNormalVector3Normal of the hit surface.
hitPointVector3Point of contact.
atCharacterPositionVector3Character position at hit.
atCharacterRotationQuaternionCharacter rotation at hit.
hitStabilityReportHitStabilityReportStability report for the hit.
QuantizeMotionSpeed(float)
A rush speed in metres per second as the wire carries it: whole centimetres per second.
public static ushort QuantizeMotionSpeed(float metresPerSecond)
Parameters
metresPerSecondfloat
Returns
QuantizeMotionYaw(Vector3)
A heading as the wire carries it: 1/65536 of a turn about world up.
public static ushort QuantizeMotionYaw(Vector3 direction)
Parameters
directionVector3
Returns
ReapplyPredictedRushStop(uint)
On a REPLAYED movement step: the rush stop a hit made after this tick, made again.
public void ReapplyPredictedRushStop(uint tick)
Parameters
tickuint
ResetGroundProbe()
Forces a full-radius ground probe on the next motor update, so a character that has just been placed does not read as airborne for a frame or three.
public void ResetGroundProbe()
Remarks
Call this for a teleport or a fresh spawn — NOT for a reconcile, which restores
LastMovementIterationFoundAnyGround authoritatively and must not have it forced.
SetFlying(bool)
Starts or stops game-master flight. SERVER ONLY: the owner learns it from the next reconcile (IsFlying), so both fly the same path from that tick. Flying lets go of a climbable and stops swimming; while it lasts nothing collides with the character and nothing holds it up or down.
public void SetFlying(bool value)
Parameters
valuebool
SetInputs(ref AICharacterInputs)
This is called every frame by the AI script in order to tell the character what its inputs are
public void SetInputs(ref AICharacterInputs inputs)
Parameters
inputsAICharacterInputs
SetInputs(ref KCCInputReplicateData)
Applies one tick of replicated input. Called from KCCPlayer.OnReplicate, once per
replicated or replayed tick — not per frame, despite the upstream sample's name for it.
public void SetInputs(ref KCCInputReplicateData inputs)
Parameters
inputsKCCInputReplicateData
SetInputs(ref KCCInputReplicateData, bool)
Applies a tick's replicated input, optionally with the controls taken away.
public void SetInputs(ref KCCInputReplicateData inputs, bool controlsSuppressed)
Parameters
inputsKCCInputReplicateDataThis tick's replicated input.
controlsSuppressedboolTrue to ignore the player's controls this tick.
Remarks
With controlsSuppressed set the move vector is zeroed, no jump,
crouch or sprint is honoured and a jump requested on the previous tick is forgotten,
but the facing is left where it was and the motor is still driven this tick. That is
what a dead or incapacitated character needs: gravity and the ground keep acting on
it, the player just cannot steer it. The virtual camera is still recorded so the aim
origin is current the moment control returns.
SettleRotation(Quaternion, bool, Quaternion, bool)
The rotation, or exactly the upright heading it is turning to once it is within SettleDegrees.
public static Quaternion SettleRotation(Quaternion rotation, bool hasHeading, Quaternion heading, bool upright)
Parameters
Returns
- Quaternion
Remarks
The turn is an exponential approach (a Slerp toward the heading every tick, then a Slerp back to upright), and in floats it never lands: a character standing still kept a rotation that changed in its last bits on every tick. The reconcile carries the rotation exactly, so that noise made every reconcile of an idle player differ from the last and none could be skipped as a repeat (CharacterPredictionController quiet reconciles). Settling exactly on the heading gives a fixed point instead. Server and owner run this same arithmetic on the same input, so it is no less deterministic than the approach it ends. Only when the character turns upright (no bonus orientation), the only case with a single heading to settle on.
SettleVelocity(Vector3, Vector3)
The velocity, or exactly zero when the character is coming to rest and is slower than SettleSpeed.
public static Vector3 SettleVelocity(Vector3 velocity, Vector3 target)
Parameters
velocityVector3targetVector3
Returns
- Vector3
Remarks
The slow-down is an exponential approach too: without this the velocity of a character that let go of the keys took seconds of ever-smaller float noise to reach zero, and each of those ticks was a reconcile that could not be skipped. A tenth of a millimetre per second is far below anything drawn; both peers run the same arithmetic.
TeleportTo(Vector3)
Moves the character to destination at once: an ability blink. Called from the ability step on
the server and the owner (and again on a replayed tick), so both place it identically; any rush ends.
public void TeleportTo(Vector3 destination)
Parameters
destinationVector3
TeleportTo(Vector3, Quaternion)
TeleportTo(Vector3), also turning the character to rotation (a blink that lands
facing what it struck). Server-side callers reach the owner through the next reconcile.
public void TeleportTo(Vector3 destination, Quaternion rotation)
Parameters
destinationVector3rotationQuaternion
TransitionToState(KCCCharacterState)
Handles movement state transitions and enter/exit callbacks
public void TransitionToState(KCCCharacterState newState)
Parameters
newStateKCCCharacterState
UpdateRotation(ref Quaternion, float)
(Called by KinematicCharacterMotor during its update cycle) This is where you tell your character what its rotation should be right now. This is the ONLY place where you should set the character's rotation
public void UpdateRotation(ref Quaternion currentRotation, float deltaTime)
Parameters
currentRotationQuaterniondeltaTimefloat
UpdateVelocity(ref Vector3, float)
(Called by KinematicCharacterMotor during its update cycle) This is where you tell your character what its velocity should be right now. This is the ONLY place where you can set the character's velocity
public void UpdateVelocity(ref Vector3 currentVelocity, float deltaTime)
Parameters
currentVelocityVector3deltaTimefloat