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