Tag Archives: spin

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

 

How to spin objects using a motion tween rotation

This video tutorial explains how to spin or rotate objects by changing the rotation effects on a motion tween. You can spin stationary or moving objects. The video is also available on YouTube here if you’d prefer to watch it there.