The physics event system in Cocos Creator 3.0 are divided into trigger events and collision events, which are generated by Trigger and Collider respectively.
When colliding, the collider will produce physical a behavior, however the trigger will not. Therefore, the trigger only performs collision detection. The collider performs both collision detection and physical simulation. The difference between them:
A Trigger is a Collider component whose Is Trigger
property is true
. When a collision occurs, the Trigger does not produce collision effect, so the Trigger is only used for collision detection.
The differences between Trigger and Collider are as follows:
- Trigger do not perform finer detection with other triggers or colliders.
- Collider do more detailed detection with other colliders, and will provide some additional data due to collisions, such as collision points, normals and so on.
The differences between Trigger events and Collision events are as follows:
- Trigger events are generated by triggers, and collision events are generated based on collision data.
- The trigger event can be generated by the trigger with another trigger or another collider.
- Collision events need to be generated by two colliders and at least one dynamic rigid body.
There are three types of Trigger Events:
Events | Description |
---|---|
onTriggerEnter |
Trigger start |
onTriggerStay |
Trigger stay |
onTriggerExit |
Trigger end |
In order to add listeners to the trigger event, you need to add the corresponding callback by registering the event:
- Get Collider through
this.getComponent(Collider)
- Register the callback of the corresponding event through the on or once method of Collider
Code example:
public start () {
let collider = this.getComponent(Collider);
collider.on('onTriggerStay', this.onTrigger, this);
}
private onTrigger (event: ITriggerEvent) {
console.log(event.type, event);
}
Collision events are generated based on collision data. Collision data only affects dynamic rigid bodies. Therefore, a dynamic rigid body is required to generate collision events.
Collision events are divided into three types:
Events | Description |
---|---|
onCollisionEnter |
Start of the collision |
onCollisionStay |
Collision hold |
onCollisionExit |
end of the collision |
In order to add a listener to the collision event, you need to add the corresponding callback by registering the event:
- Get Collider through
this.getComponent(Collider)
- Register the callback of the corresponding event through the on or once method of Collider
Code example:
public start () {
let collider = this.getComponent(Collider);
collider.on('onCollisionStay', this.onCollision, this);
}
private onCollision (event: ICollisionEvent) {
console.log(event.type, event);
}
Note:
Collider
is the parent class of all collision components.- Collision events are in physical elements, and all collider components on this element will receive collision events.