Kategorien
HTML5 JavaScript three.js WebGL

Three.js Camerasteuerung mit der Tastatur

Um mit der Tastatur (a,w,s,d und q,e und t,g,f,h) in einem three.js 3D-Projekt die Kamera zu bewegen, sind ein paar einfach Schritte nötig.

in der init-Methode

document.addEventListener( 'keypress', onDocumentKeyPress, false );

und eine einfache Methode

  function onDocumentKeyPress( event ) {

        var keyCode = event.which;
        var positionDelta = 70;
        var rotationDelta = 0.1;
        //console.log(keyCode);
        //A
        if ( keyCode == 97 )
        {

            camera.position.x -= positionDelta;
        }
        //D
        else if ( keyCode == 100 )
        {

            camera.position.x += positionDelta;
        }
        //W
        else if ( keyCode == 119 )
        {
            camera.position.z -= positionDelta;
        }
        //S
        else if ( keyCode == 115 )
        {
            camera.position.z += positionDelta;

        }
        //Q
        else if ( keyCode == 113 )
        {
            camera.position.y += positionDelta;
        }
        //E
        else if ( keyCode == 101 )
        {
            camera.position.y -= positionDelta;

        }
        //T
        else if ( keyCode == 116 )
        {
            camera.rotation.x += rotationDelta;

        }
        //G
        else if ( keyCode == 103 )
        {
            camera.rotation.x -= rotationDelta;

        }
        //F
        else if ( keyCode == 102 )
        {
            camera.rotation.y += rotationDelta;

        }
        //H
        else if ( keyCode == 104 )
        {
            camera.rotation.y -= rotationDelta;
        }
    }