Rotate/Pan Camera using left/right arrow keys instead of mouse in A-Frame

Viewed 31

This may have been asked numerous times, but I can't get a clear "newbie" plan of action.

Building Aframe experiences to showcase some interiors for numerous client presentations—this will be show on a desktop browser only, and I need to be able to control pan/rotate/turn-around camera movement with left and right arrow keys instead of relying on the mouse, as many clients have found this cumbersome. I just need to control this like an old first-person shooter with four arrow buttons.

Is there a simple way to do this? I've seen various permutations of this question but no simple solution so far. Thanks!

1 Answers

A simple keyboard input look component:

AFRAME.registerComponent('kbd-look-controls', {
    schema: {
        speed: {type: 'number', default: 2}
    },

    init: function () {
        this.bindFunctions();
        this.addEventListeners();
        this.keyPressed = {
            'ArrowUp': false,
            'ArrowDown': false,
            'ArrowLeft': false,
            'ArrowRight': false
        }
    },

    remove: function () {
        this.removeEventListeners();
    },

    tick: function(time, delta) {
        var data = this.data;
        var object3D = this.el.object3D;

        const angleDelta = 0.01 * data.speed * (delta / 16);

        if (this.keyPressed['ArrowUp']) {
            object3D.rotation.x = object3D.rotation.x + angleDelta;
        }
        if (this.keyPressed['ArrowDown']) {
            object3D.rotation.x = object3D.rotation.x - angleDelta;
        }
        if (this.keyPressed['ArrowLeft']) {
            object3D.rotation.y = object3D.rotation.y + angleDelta;
        }
        if (this.keyPressed['ArrowRight']) {
            object3D.rotation.y = object3D.rotation.y - angleDelta;
        }
    },

    bindFunctions() {
        this.onKeyUp = this.onKeyUp.bind(this);
        this.onKeyDown = this.onKeyDown.bind(this);
    },

    addEventListeners() {
        window.addEventListener('keydown', this.onKeyDown);
        window.addEventListener('keyup', this.onKeyUp);
    },

    removeEventListeners() {
        window.removeEventListener('keydown', this.onKeyDown);
        window.removeEventListener('keyup', this.onKeyUp);
    },

    onKeyUp: function (evt) {
        this.keyPressed[evt.code] = false;
    },

    onKeyDown: function (evt) {
        this.keyPressed[evt.code] = true;
    }

})

Sample usage:

<a-entity camera kbd-look-controls="speed: 2.5" position="0 1 0"></a-entity>

This is one approach to getting to achieve your functionality.

Using wasd-controls component as well can be undesirable, since the wasd-controls also listens to the arrow keys.

Doesn't work with the look-controls component since it's also adjusting the rotation.

Related