Rigid Bodies and Collision in PlayCanvas

This tutorial explains how to add the Rigid Body and Collision components to objects in your game so that your objects can move around and interact in a realistic way and so that you can detect when different objects collide in your game.

Rigid bodies allow the objects in your game to act under the control of physics. This means that your objects will be able to receive forces and move around in a realistic way. In order for an object to be able to interact with other objects and be under the influence of gravity or different forces (that can be controlled by scripts), it must have a Rigid Body component. You can change the properties of a rigid body such as friction, restitution (bounciness), mass, and so on.

The Collision component in PlayCanvas will give an object its physical form and change the way it behaves. There are several types of colliders (collision types) such as box, sphere, capsule, etc. If you give a box object a box collider, it will behave like a box. This means it will move around, slide, bounce, fall, and collide with other objects the way that a box would. If you give a sphere or ball object a sphere collider, then it will be able to bounce and roll around just like a real sphere or ball would. The Collision component is necessary for collision detection and triggers (something we will look at in another tutorial).

Watch the video below and then scroll down to see the sample code used for basic collision detection in the video.

Sample code for the collider.js script:

pc.script.create('collider', function (app) {
    // Creates a new Collider instance
    var Collider = function (entity) {
        this.entity = entity;
    };

    Collider.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
            this.entity.collision.on('collisionstart', this.onCollisionStart, this);
        },

        onCollisionStart: function(result){
            if(result.other.rigidbody){
                this.entity.destroy();
            }
        }
        
        
    };

    return Collider;
});