"Universal" fly camera

I’ve found in another engines (Babylon) a sample with universal camera that works in PC as well as smartphones etc being controlled by keyboard and mouse in PC and with virtual joesticks in phones and so.

Is there something like that in Playcanvas?

Thank you in advance.

Hi @VictorF !
I am 99% sure it works on mobile and gamepads as well.
Go to the asset store (Click button on the top left header of the asset picker), go to scripts, and there is a fly camera scripts.

I could crack one out for you real quick for you if you want, but only for pc as I do not have a mobile device to test on.

If the playcanvas store one doesn’t work and you make one, I could test it.

Here ya go

var Spectatorcamera = pc.createScript('spectatorcamera');

Spectatorcamera.attributes.add("speed", {
    type: "number"
});

Spectatorcamera.attributes.add("sensitivity", {
    type: "number"
});

Spectatorcamera.prototype.initialize = function() {
    this.force = new pc.Vec3();
    this.eulers = new pc.Vec3();
    window.lockMouse = true;
    var app = this.app;
    app.mouse.on("mousemove", this._onMouseMove, this);
    app.mouse.on("mousedown", function () {
        if(lockMouse)
        {
            app.mouse.enablePointerLock();
        }
    }, this);
};

// update code called every frame
Spectatorcamera.prototype.update = function(dt) {
    this.app.mouse.enablePointerLock();
    var app = this.app;
    this.speedo = this.speed;
    if (app.keyboard.isPressed(pc.KEY_SHIFT))
    {
        this.speedo = (this.speed*6);
    }
    if (app.keyboard.isPressed(pc.KEY_A))
    {
        this.entity.translateLocal(-(this.speedo*dt), 0*dt, 0*dt);
    }
    if (app.keyboard.isPressed(pc.KEY_D))
    {
        this.entity.translateLocal(this.speedo*dt, 0*dt, 0*dt);
    }
    if (app.keyboard.isPressed(pc.KEY_E))
    {
        this.entity.translateLocal(0*dt, this.speedo*dt, 0*dt);
    }
    if (app.keyboard.isPressed(pc.KEY_Q))
    {
        this.entity.translateLocal(0*dt, -(this.speedo*dt), 0*dt);
    }
    if (app.keyboard.isPressed(pc.KEY_S))
    {
        this.entity.translateLocal(0*dt, 0*dt, this.speedo*dt);
    }
    if (app.keyboard.isPressed(pc.KEY_W))
    {
        this.entity.translateLocal(0*dt, 0*dt, -(this.speedo*dt))
    }
    this.entity.setLocalEulerAngles(this.eulers.y, this.eulers.x, 0);
};

Spectatorcamera.prototype._onMouseMove = function (e) {
    if (pc.Mouse.isPointerLocked() || e.buttons[0])
    {
        this.eulers.x -= this.sensitivity * e.dx;
        this.eulers.y -= this.sensitivity * e.dy;
    }
    this.eulers.y = pc.math.clamp(this.eulers.y, -89, 89);
};

Its kinda janky frankenstein code from a customized first person camera so the pointerlock is a bit agressive (dont know how to fix that), but otherwise it moves exactly like the editor camera. Just apply it to any otherwise empty camera entity, make sure to parse and use attribute numbers.

@KPal

Yes. Grab this one:

1 Like