Simple Mobile Controller Script

I’m looking for a simple script that will move a ball (as in the First Project Scene) by touch for a mobile device. Or by tilting a mobile device. What approach would be best? Is there a tutorial for either of these?

All tutorials are here: http://developer.playcanvas.com/en/tutorials/
You can use left panel to search by tag, there is Touch tag as well.

For tilting you need Gyroscope, and that is accessible using Device Orientation API.

1 Like

The Orbit camera tutorial works really well

http://developer.playcanvas.com/en/tutorials/orbit-camera/

It is modular code, there is the central orbit camera class which handles most stuff for rotation, interpolation and bounds.

The other two classes “just” calculate the input values for relative rotation and assign this to the orbit camera

this.orbitCamera.pitch -= (touch.y - this.lastTouchPoint.y) * this.orbitSensitivity;
this.orbitCamera.yaw -= (touch.x - this.lastTouchPoint.x) * this.orbitSensitivity;

Both input scripts can be activated at the same time, so you can have comparable control for all platforms.

The implementation of the Device Orientation API is really really buggy on android. But PlayCanvas has support for WebVR and also provides the polyfill for android. there is a “magic window” you can use, if you only want the input information vom WebVr without the DoubleScreen.

With help of that features i could write a fourth script to provide Device-Orientation in combination with touch input!

var GyroOrientation = pc.createScript('input/GyroOrientation');

GyroOrientation.prototype.initialize = function() {
    console.log('vrDisplay?', this.app.vr.display);
    if (this.app.vr.display) {
        this.entity.camera.vrDisplay = this.app.vr.display;
        
        this.orbitCamera = this.entity.script['orbitCamera'];
        
        var currentEuler = this.app.vr.display.combinedViewInv.getEulerAngles().clone();
        this.lastRot = new pc.Quat().setFromEulerAngles(currentEuler.x, currentEuler.y, currentEuler.z);
    }
};

GyroOrientation.prototype.update = function(dt) {
    if (!this.app.vr.display) {
        return;
    }
    
    var currentEuler = this.app.vr.display.combinedViewInv.getEulerAngles().clone();
    var currentRot = new pc.Quat().setFromEulerAngles(currentEuler.x, currentEuler.y, currentEuler.z);
    
    currentRot.invert().mul(this.lastRot);
    
    var euler = currentRot.getEulerAngles();
    var pitch = -euler.x;
    var yaw = -euler.y;
    
    this.orbitCamera.yaw += yaw;
    this.orbitCamera.pitch += pitch;
    
    this.lastRot.setFromEulerAngles(currentEuler.x, currentEuler.y, currentEuler.z);
};

there is no support for “roll”, but i don’t miss that feature :slight_smile:

2 Likes

p.s.: you have to active VR in the rendering settings in the editor

1 Like

Thanks for the input guys. My Gyro is now working!

I made joystick

https://playcanvas.com/editor/scene/727478

Record_2019_03_19_00_39_50_633

3 Likes