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
                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

    return Rotate;