Files
engine/docs/en/physics/controller.md
2024-08-05 16:03:57 +08:00

2.9 KiB

order, title, type, label
order title type label
4 Character Controller Component Physics Physics

The character controller is a very important functional component provided by the physics engine. With the character controller, it is easy to add physical effects to the movement of animated characters. For example, you can set parameters to prevent the character from climbing slopes of a certain angle, or avoid collision feedback with other colliders during the character's movement. In fact, the character controller is just an advanced encapsulation of the collider, implementing various advanced character control behaviors through collision detection. Therefore, the creation and use of the character controller component are very similar to the collider component.

const physicsCapsule = new CapsuleColliderShape();
physicsCapsule.radius = radius;
physicsCapsule.height = height;
const characterController = capsuleEntity.addComponent(CharacterController);
characterController.addShape(physicsCapsule);

Like the collider component, it is constructed by creating a ColliderShape and adding it to the component, giving the character controller a specific shape. However, two points need to be emphasized here:

  1. The character controller does not support compound shapes, so only one ColliderShape can be added.
  2. The character controller currently only supports CapsuleColliderShape and BoxColliderShape, with CapsuleColliderShape being the most commonly used.

Subsequent behaviors of the character controller are controlled through various parameters and methods of CharacterController, with the most important being the move function:

class Controller extends Script {
    onPhysicsUpdate() {
        const fixedTimeStep = this.engine.physicsManager.fixedTimeStep;
        const character = this._character;
        const flag = character.move(this._displacement, 0.1, fixedTimeStep);
        if (flag | ControllerCollisionFlag.Down) {
            character.move(new Vector3(0, -0.2, 0), 0.1, fixedTimeStep);
        }
        this._displacement.setValue(0, 0, 0);
    }
}

You can specify the character's displacement in the move method, and this method returns a composite value of an enumeration type. Through this enumeration type ControllerCollisionFlag, you can determine whether the character controller has collided with other collider components:

export enum ControllerCollisionFlag {
  /** Character is colliding to the sides. */
  Sides = 1,
  /** Character has collision above. */
  Up = 2,
  /** Character has collision below. */
  Down = 4
}

This determines how the character's next animation and movement will proceed. In the example below, you can control the character's movement via the keyboard, allowing it to climb or jump over specific obstacles.