2

1.- THREEJS: una buena elección como motor javascript 3D

Si exigimos un entorno abierto y multiplataforma para nuestros juegos 2D y 3D, que además sea programable en javascript y que implemente el estandar WebGL (esto sería opcional, claro), creo que Three.js es una buena solución.


Three.js dispone de distintas geometrías estandar -aparte de permitir geometrías personalizadas definiendo los puntos uno por uno o mediante bucles-, diferentes materiales que reaccionan también de diferente manera según el tipo de luz que reciben, dos o tres tipos de cámaras diferentes y varios objetos de tipo render. Es un gustazo programar con Three.js. Además existen multitud de scripts de la comunidad que permiten realizar tares muy facilmente, pudiendo implementar en un plis plas controles que parametricen todos los objetos que tenemos en la escena, mover la cámara, etc. El manejo de texturas es sencillo y con un resultado a veces espectacular. Tenemos también, aparte del render normal THREE.WebGLRenderer(), otro THREE.CSS3DRenderer() basado en transformaciones CSS3 compatible por tanto con dispositivos móviles, que permite tratar elementos HTML como div, textarea o button en un mundo 3D.


Por si alguien tiene curiosidad en cómo es la programación, abajo dejo un código totalmente funcional que renderiza un cubo sobre un plano aplicando luces y sombras. Para ejecutar el ejemplo en nuestro ordenador, solo tenemos que conseguir la librería three.js, por ejemplo de github: https://github.com/mrdoob/three.js/


Podemos descargar solo la librería three.js de la carpeta build del repositorio, en caso de no querer descargar todo el repositorio que son unos 100 MB con ejemplos, material multimedia, docs, etc.


Saludos

Vicent


Espero que alguien se anime con three.js y poder compartir conocimiento.


Bueno, ahí va "Simple mesh":


<!DOCTYPE html>

<html>

<head>

    <title>01.02 - Simple mesh</title>

<script src="three.js"></script>

    <style>

        body {

            /* set margin to 0 and overflow to hidden, to go fullscreen */

            margin: 0;

            overflow: hidden;

        }

    </style>

</head>

<script>


// global variables

    var renderer;

    var scene;

    var camera;


    /**

     * Initializes the scene, camera and objects. Called when the window is

     * loaded by using window.onload (see below)

     */

function init() {


        // create a scene, that will hold all our elements such as objects, cameras and lights.

        scene = new THREE.Scene();


        // create a camera, which defines where we're looking at.

        camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);


        // create a render, sets the background color and the size

        renderer = new THREE.WebGLRenderer();

        renderer.setClearColor(0x000000, 1.0);

        renderer.setSize(window.innerWidth, window.innerHeight);

        // habilitamos a renderer para sombras

        renderer.shadowMapEnabled = true;


        // create the ground plane

        var planeGeometry = new THREE.PlaneGeometry(20, 20);

        var planeMaterial = new THREE.MeshLambertMaterial({color: 0xcccccc});

        var plane = new THREE.Mesh(planeGeometry, planeMaterial);

        // El plano recibirá sombra

        plane.receiveShadow = true;


        // rotate and position the plane

        plane.rotation.x = -0.5 * Math.PI;

        plane.position.x = 0;

        plane.position.y = -2;

        plane.position.z = 0;


        // add the plane to the scene

        scene.add(plane);


        // create a cube: ancho, alto, profundidad

        var cubeGeometry = new THREE.BoxGeometry(6, 4, 10);

        var cubeMaterial = new THREE.MeshLambertMaterial({color: 'red'});

        var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);


        // cube proyecta sombra

        cube.castShadow = true;


        // add the cube to the scene

        scene.add(cube);


        // position and point the camera to the center of the scene

        camera.position.x = 15;

        camera.position.y = 16;

        camera.position.z = 13;

        camera.lookAt(scene.position);


        // add spotlight for the shadows

        var spotLight = new THREE.SpotLight(0xffffff);

        spotLight.position.set(10, 20, 20);

        spotLight.shadowCameraNear = 20;

        spotLight.shadowCameraFar = 50;

        spotLight.castShadow = true;


        scene.add(spotLight);



        // add the output of the renderer to the html element

        document.body.appendChild(renderer.domElement);


        // call the render function, after the first render, interval is determined

        // by requestAnimationFrame

        render();

    }


    /**

     * Called when the scene needs to be rendered. Delegates to requestAnimationFrame

     * for future renders

     */

    function render() {

        // render using requestAnimationFrame

        requestAnimationFrame(render);

        renderer.render(scene, camera);

    }



    /**

     * Function handles the resize event. This make sure the camera and the renderer

     * are updated at the correct moment.

     */

    function handleResize() {

        camera.aspect = window.innerWidth / window.innerHeight;

        camera.updateProjectionMatrix();

        renderer.setSize(window.innerWidth, window.innerHeight);

    }


    // calls the init function when the window is done loading.

  window.onload = init;

    // calls the handleResize function when the window is resized

    window.addEventListener('resize', handleResize, false);


</script>

<body>

</body>

</html>

Escribe tu comentario
+ 2