Category Archives: PlayCanvas

Moving an object with force in PlayCanvas

This tutorial explains how to use keyboard input to move an object around. But rather than telling the object how far it needs to move (like in this other tutorial), we will apply force to the object instead. This means that the object your moving can also hit other objects and interact with them rather than just going through them.

Step 1 – Setting up the object you want to move

To begin with, you need to create an object or use a model that you want to move. Then you need to add a Rigid Body component and a Collision component so that this object can collide and interact with other objects in the scene. For this example, I have added a Box entity (click + in the Hierarchy and then click Box) but you can use another 3D shape or model.

3dobject
Then you need to select the object and click on Add Component (in the Inspector panel on the left side of the screen) and choose the Collision component. If you have a box shape (entity) then you should set the Collision Type to Box (if you have a sphere shape, then select Sphere for Type, and so on).

Match your collision settings up so they look like the settings shown below. The numbers in the Half Extents property boxes should be half the numbers in the Scale property boxes above it. Eg. if the scale X property of the box has a value of 4 then the Half Extents X value should be 2.

box_collision

Now click on Add Component again and this time add the Rigid Body component. Change the Type to Dynamic and modify the values so they are the same as those below (experiment with these values later to get the effect you want).

rigid_body
It is important to make sure any other objects that this object will interact with also have Rigid Body and Collision components attached to them. For example, if you don’t want this object to fall through your ground in the scene, then the ground object should have a Static type Rigid Body and a Collision component.

If you want other objects to not be moved by this object, they should have a Static type Rigid Body and Collision component. Otherwise, if you want this object to move other objects when it touches them, add Dynamic type Rigid Body and Collision components to those other objects.

Adding a script to the object

Click on + in the Assets panel and choose Script to create a new script.

create_script
Call the new script moveWithForce.js and hit Enter to create the script.

script_name

Now you need to attach the script to the 3D object or model you want to move or control. Select the 3D object (eg. box) and then click on Add Component and select Script. Drag the moveWithForce.js script onto the Scripts component on the object in the Inspector panel and then let go. The script should now be attached to the object.

script_attached

 

Writing the code

Double-click on the moveWithForce.js script you just created in the Assets panel and replace all of the existing code with the following code in the Code Editor window:

// Add this code to any object you want to move with force
// Object that this script is attached to must have collision component and DYNAMIC rigid body component

pc.script.attribute("power", "number", 1000);  // set power to initial value of 1000
pc.script.create('moveWithForce', function (app) {
    // create force variable
    var force = new pc.Vec3();
    // Creates a new MoveWithForce instance
    var MoveWithForce = function (entity) {
        this.entity = entity;
    };

    MoveWithForce.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
            // Check for required components
            if (!this.entity.collision) {
                console.error("First Person Movement script needs to have a 'collision' component");
            }
            
            if (!this.entity.rigidbody || this.entity.rigidbody.type !== pc.BODYTYPE_DYNAMIC) {
                console.error("First Person Movement script needs to have a DYNAMIC 'rigidbody' component");
            }
            
            // Listen for keyboard press events
            app.keyboard.on(pc.EVENT_KEYDOWN, this._onKeyDown, this);
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {

            // movement
            var x = 0;
            var z = 0;
            var y = 0;
            
            // Use W-A-S-D keys to move player around and Space to make player jump
            // Check for key presses
            if (app.keyboard.isPressed(pc.KEY_LEFT)) {
                x -= 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_RIGHT)) {
                x += 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_UP)) {
                z -= 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_DOWN)) {
                z += 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_SPACE)) {
                console.log("space pressed");
                y += 0.05;
            }
            
            // use direction from keypresses to apply a force to the character (x and z axes)
            if (z !== 0) {
                force.set(0, 0, z).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
            
            if (x !== 0) {
                force.set(x, 0, 0).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
            
            // use direction from keypresses to apply a force to the character (y axis)
            if (y !== 0) {
                force.set(x, y, z).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
        },
        
        _onKeyDown: function (event) {
            // When the space bar is pressed this scrolls the window.
            // Calling preventDefault() on the original browser event stops this.
            event.event.preventDefault();
            console.log("Scrolling disabled");
        }
    };

    return MoveWithForce;
});

Now click on Save and then go back to the game Editor window. That’s it! Launch your game by clicking on the Launch (play) button and you should now be able to control the 3D object/model by using the keyboard to move it around and make it jump. The code is set up to move the object using the arrow keys and space bar to jump. However, you can change these keys and you can also remove the code that makes the object jump if you don’t want to make it jump in the game.

 

 

 

Controlling audio with scripts

This tutorial explains how to control the audio in your game using scripts. You can play, stop, pause and resume sound effects and songs in your game when certain events occur by controlling the sound with code. This video explains how to do that and if you scroll down you will find the sample code.

The following sample code is used to control an audio source/slot called “song” that is attached to the same entity that the script is attached to. The filename of this script is playsong.js.

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

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                this.entity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                this.entity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

The following sample code is used to control an audio source/slot called “song” that is attached to a Sound entity called “mySound“. The script can be attached to any other entity in the game scene. The filename of this script is playsong.js.

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

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            // creates variable for audio entity
            var AudioEntity = app.root.findByName('mySound');
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                AudioEntity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                AudioEntity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

South Of The Border by Audionautix is licensed under a Creative Commons Attribution licence (https://creativecommons.org/licenses/by/4.0/)
Artist: http://audionautix.com/

Adding sound to a game in PlayCanvas

This tutorial explains how to add sound effects and background music to your game in PlayCanvas. You can add sounds that can be heard from anywhere in the game or attach sounds to objects that can only be heard when your character is near them in the game.

You can also add sounds that automatically play and loop in the background and you can also control when sounds play and stop using code. Using code to control sound will be explained in the next tutorial. Watch the video below to see how to add sound to your game.

South Of The Border by Audionautix is licensed under a Creative Commons Attribution licence (https://creativecommons.org/licenses/by/4.0/)
Artist: http://audionautix.com/

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;
});

Rotating objects with keyboard input in PlayCanvas

In this tutorial you will learn how to rotate an object using code in PlayCanvas. This means that you can allow users to spin an object when they press a key on the keyboard. You will also be introduced to variables in JavaScript. Watch the video below and then scroll down to view the sample code.

Sample JavaScript code for the rotate.js script:

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

    Rotate.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            // set the angle to 0
            var angle = 0;
            
            // change the angle of the box when a key is pressed
            if(app.keyboard.isPressed(pc.KEY_LEFT)){
                angle = -2;
            }
            
            else if(app.keyboard.isPressed(pc.KEY_RIGHT)){
                angle = 2;
            }
            
            // update the angle of the box to make it spin on the y axis
            this.entity.rotateLocal(0,angle,0);
        }
    };

    return Rotate;
});

 

Particle Systems in PlayCanvas

This video tutorial explains how to add particle systems to your PlayCanvas game. A particle system allows you to add a range of animated effects such as smoke, fog, bubbles, flames, and sparks.

Tip: You can also use an image for your particles by dragging an image that you have uploaded to PlayCanvas (eg. JPG or PNG image) onto the Color Map property on the particle system in the Inspector panel.

Moving objects with keyboard input in PlayCanvas

If you watched the previous tutorial you would have learned how to make an object move on its own using JavaScript code. In this tutorial, we will make an object move around using keyboard input. That is, if the left arrow key is pressed on the keyboard then we can make the object move left. If the right arrow key is pressed on the keyboard then we can make the object move right, and so on…

Keyboard input will be very useful in your games eg. to make a player jump, to move around, pick up objects or enter your name in the high score book! Watch the video to find out how to add keyboard input to your games and then try out the sample code further down the page.

Here is the sample code for this tutorial. Make sure you create a new script asset called move.js and then add it as a component to your 3D object (eg. a box). Then add the code to the move.js script.

In the code, you will see app.keyboard.isPressed – this will check if the key is being pressed during the current frame. If you hold down the key, the object will keep moving. If you use another method called app.keyboard.wasPressed instead it will only check if the key was pressed in the current frame (it will detect one keypress and won’t keep the object moving when you hold the key down).

pc.script.create('move', function (app) {
 // Creates a new Move instance
 var Move = function (entity) {
 this.entity = entity;
 };
 
 Move.prototype = {
 // Called once after all resources are loaded and before the first update
 initialize: function () {
 },
 
 // Called every frame, dt is time in seconds since last update
 update: function (dt) {
 if(app.keyboard.isPressed(pc.input.KEY_RIGHT)){
 this.entity.translateLocal(0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_LEFT)){
 this.entity.translateLocal(-0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_UP)){
 this.entity.translateLocal(0,0.1,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_DOWN)){
 this.entity.translateLocal(0,-0.1,0);
 }
 }
 };
 
 return Move;
});

Make a 3D object move with code in PlayCanvas

In this tutorial we will start writing our very lines of JavaScript code in the PlayCanvas code editor! To start with, we will make a 3D object (eg. a box or sphere) move around the screen on its own. Watch the video below and then scroll down to see the sample code and try it out for yourself.

Here is the sample code for this tutorial. Make sure you create a new script asset called move.js and then add it as a component to your 3D object (eg. a box). Then add the code to the move.js script. Launch your game and then watch the object start moving to the right (if your object moves to the left, then your camera is on the opposite side of the object). Try changing the x, y, and z translateLocal parameters to make your object move in different directions at different speeds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
pc.script.create('move', function (app) {
 // Creates a new Move instance
 var Move = function (entity) {
 this.entity = entity;
 };
 
 Move.prototype = {
 // Called once after all resources are loaded and before the first update
 initialize: function () {
 },
 
 // Called every frame, dt is time in seconds since last update
 update: function (dt) {
 this.entity.translateLocal(0.01,0,0);
 }
 };
 
 return Move;
});

An overview of scripts in PlayCanvas

This tutorial will not show how to write code in PlayCanvas just yet, but will give you an overview of how scripts work in PlayCanvas and the structure of a basic script. It is important to watch this tutorial first especially if you don’t have any coding experience in JavaScript. The next tutorial will show you how to start writing your JavaScript code for your games.

Here is the sample code from the tutorial (it is just a template and doesn’t actually make your game do anything):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
pc.script.create('test', function (app) {
 // Creates a new Test instance
 var Test = function (entity) {
 this.entity = entity;
 };
 
 Test.prototype = {
 // Called once after all resources are loaded and before the first update
 initialize: function () {
 },
 
 // Called every frame, dt is time in seconds since last update
 update: function (dt) {
 }
 };
 
 return Test;
});

Skyboxes in PlayCanvas

In this tutorial you will be introduced to Skyboxes and CubeMaps in PlayCanvas. A skybox is a method of creating backgrounds to make the environment in a 3D game look bigger than it really is. Sky, distant mountains, hills or buildings are projected onto the six interior faces of the cube using a technique called cube mapping which creates an illusion of distant 3D surroundings.

A CubeMap in PlayCanvas is stored as six square images of textures. You can download images to use as a CubeMap for your game’s skybox (some links are included below). Below is an example of a cube map.

An example of cube mapping. Image by Arieee (redistributed using the CC BY-SA 3.0 license).
An example of cube mapping. Image by Arieee (redistributed using the CC BY-SA 3.0 license).

Watch the video below and then scroll down to find some links to downloadable cube maps for your own project.

Here are some links to free cube maps you can use in your own projects:

Lighting in PlayCanvas

In this tutorial you will learn how to add and modify lighting in your game. You can use different types of lights and have multiple lights in any scenes to change the feel and atmosphere of the game. The three types of lights you can use are:

  • Directional light – light rays come from one direction
  • Point light – a sphere of light that shines in all directions
  • Spot light – a cone of light

Watch the video below to see how you can use lighting in your own PlayCanvas game.

Entities and materials in PlayCanvas

In this tutorial you will learn more about entities and how to modify a Box entity to make a ground or floor for your game’s scenes. You will also learn how to use materials to give 3D objects some colour and apply detailed patterns and textures using assets.

A repeating grass pattern image like the one shown in this tutorial can be downloaded from here.

Tip: You can do a Google Images search for textures and patterns using keywords such as “brick pattern tiled”, “repeat brick pattern” or “brick pattern seamless”.

Getting started with PlayCanvas

PlayCanvas is a 3D game development environment in the cloud. You can use PlayCanvas to make your own 3D games and code them in the JavaScript programming language using a web browser like Chrome or Firefox.

In this tutorial you will learn about the PlayCanvas features and tools and how to create, move, rotate, and resize 3D shapes. Watch the video below to get started with PlayCanvas.