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