Interact/rotate object using Three.js

时间:2015-07-31 19:27:54

标签: three.js

I am using the basic example on three.js but am unable to interact with the object to rotate via mouse interaction. Am I missing something obvious? My desired functionality is to rotate an object (such as a box) left,right,up,down, etc. The code I am using is as follows:

<!DOCTYPE html>
<script src="scripts/three.min.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My first Three.js app</title>
<style>
    body {
        margin: 0;
    }

    canvas {
        width: 100%;
        height: 100%;
    }
</style>
</head>
<body>
<script src="scripts/three.min.js"></script>
<script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

        var renderer = new THREE.WebGLRenderer();
        renderer.setSize( window.innerWidth, window.innerHeight );
        document.body.appendChild( renderer.domElement );

        var geometry = new THREE.BoxGeometry( 3, 1, 1 );
        var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
        var cube = new THREE.Mesh( geometry, material );
        scene.add( cube );

        camera.position.z = 5;

        var render = function () {
            requestAnimationFrame( render );

            cube.rotation.x += 0.01;
            cube.rotation.y += 0.01;

            renderer.render(scene, camera);
        };

        render();
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

You are missing EventListeners, your scene doesnt know about your mouse moving.

See this simple example from mr.doob on how to spin a cube with the mouse: http://mrdoob.github.io/three.js/examples/canvas_geometry_cube.html

Similiar to the rotation on the Y-Axis (left, right) you can add rotation on the X-Axis (up, down) too.