Physics

While functioning as a kinematic character controller, the CharacterMovement component, also known as the motor, can seamlessly perform physics interactions, including pushing rigid bodies or other characters, responding to external forces, and handling dynamic platforms.

The following example demonstrates how to utilize the Character LaunchCharacter function to implement a bouncer.

public class Bouncer : MonoBehaviour
{
    public float launchImpulse = 15.0f;

    public bool overrideVerticalVelocity;
    public bool overrideLateralVelocity;

    private void OnTriggerEnter(Collider other)
    {
        if (!other.CompareTag("Player"))
            return;

        if (!other.TryGetComponent(out Character character))
            return;
        
        character.PauseGroundConstraint();
        character.LaunchCharacter(transform.up * launchImpulse, overrideVerticalVelocity, overrideLateralVelocity);
    }
}

It's important to note the use of PauseGroundConstraint. This temporarily disables the character's ground constraint, allowing the character to freely leave walkable ground.

The following example demonstrates how to extend a Character through composition to apply a landing force. This utilizes the Landed event.

public class ApplyLandingForce : MonoBehaviour
{
    public float landingForceScale = 1.0f;
    
    private Character _character;

    private void Awake()
    {
        _character = GetComponent<Character>();
    }

    private void OnEnable()
    {
        _character.Landed += OnLanded;
    }

    private void OnDisable()
    {
        _character.Landed -= OnLanded;
    }

    private void OnLanded(Vector3 landingVelocity)
    {
        Rigidbody groundRigidbody = _character.characterMovement.groundRigidbody;
        if (!groundRigidbody)
            return;
        
        Vector3 force = _character.GetGravityVector() *
                        (_character.mass * landingVelocity.magnitude * landingForceScale);
            
        groundRigidbody.AddForceAtPosition(force, _character.position);
    }
}

Here, the landing force is calculated as (characterMass * characterGravity * landingVelocity * landingForceMag) and is applied along the character's gravity direction.

Last updated