2013-07-11 7 views
2

Как рисовать простой квадрат с помощью BufferGeometry? Например, BufferGeometry рисует 120000 треугольников, и я хочу сбить его до двух, которые образуют простой квадрат.Как нарисовать простой квадрат с помощью BufferGeometry?

<html> 
<head> 
    <title>test app</title> 
    <style>canvas { width: 100%; height: 100% }</style> 
</head> 
<body> 
    <script src="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.CubeGeometry(1,1,1); 
     var triangles = 2; 

     var geometry = new THREE.BufferGeometry(); 
     geometry.attributes = { 
      index: { 
       itemSize: 1, 
       array: new Uint16Array(triangles * 3), 
       numItems: triangles * 3 
      }, 
      position: { 
       itemSize: 3, 
       array: new Float32Array(triangles * 3 * 3), 
       numItems: triangles * 3 * 3 
      }, 
      normal: { 
       itemSize: 3, 
       array: new Float32Array(triangles * 3 * 3), 
       numItems: triangles * 3 * 3 
      }, 
      color: { 
       itemSize: 3, 
       array: new Float32Array(triangles * 3 * 3), 
       numItems: triangles * 3 * 3 
      } 
     } 

     var color = new THREE.Color(); 

     var indices = geometry.attributes.index.array; 
     var positions = geometry.attributes.position.array; 
     var normals = geometry.attributes.normal.array; //not setting normals - is it relevant if there is no light defined? 
     var colors = geometry.attributes.color.array; 

     for (var i = 0; i < indices.length; i ++) { 

       indices[ i ] = i % (3 * 1); // How to set indices???? 

     } 

     for (var i = 0; i < positions.length; i += 9) { 

      //I know these will make two triangles at same position, but i want to see them appear first.. 
      positions[ i ]  = 0; 
      positions[ i + 1 ] = 0; 
      positions[ i + 2 ] = 0; 

      positions[ i + 3 ] = 0; 
      positions[ i + 4 ] = 1; 
      positions[ i + 5 ] = 0; 

      positions[ i + 6 ] = 1; 
      positions[ i + 7 ] = 0; 
      positions[ i + 8 ] = 0; 

      color.setRGB(55, 202, 55); 

      colors[ i ]  = color.r; 
      colors[ i + 1 ] = color.g; 
      colors[ i + 2 ] = color.b; 

      colors[ i + 3 ] = color.r; 
      colors[ i + 4 ] = color.g; 
      colors[ i + 5 ] = color.b; 

      colors[ i + 6 ] = color.r; 
      colors[ i + 7 ] = color.g; 
      colors[ i + 8 ] = color.b; 
     }   

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

     camera.position.z = -5; 

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

      square.rotation.x += 0.1; 
      square.rotation.y += 0.1; 

      renderer.render(scene, camera); 
     }; 

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

+0

Не могли бы вы показать нам свой код и то, что вы пробовали? Нам будет намного легче помочь вам, если вы это сделаете, и мы с большей вероятностью поставим вам время, чтобы помочь вам, поскольку мы сможем увидеть, что вы поставили время, чтобы попытаться решить проблему сам. –

+0

Спасибо за ответ, я добавил полный код к моему вопросу, он ничего не показывает. – pera

ответ

2

Вот решение ваших проблем: Поскольку камера ближние и дальнее зрение составляет от 0,1 до 1000

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

Тогда ваши вершины г позиции должны быть между этим диапазоном , Поэтому, пожалуйста, измените ваш код от

positions[ i + 2 ] = 0; 

в

positions[ i + 2 ] = 1; 

Кроме того, кажется, что ваш код, не хватает этих частей:

geometry.addAttribute('index', new THREE.BufferAttribute(indices, 3)); 
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3)); 
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3)); 

для полного фиксированного кода, пожалуйста, обратитесь с этим здесь: http://learn-daily.com/three-js-drawing-flying-triangle-using-buffergeometry/

+0

у вас по-прежнему есть один треугольник, а не квадрат, но я получаю его отсюда :) – pera

+0

В последних версиях three.js атрибут индекса должен быть установлен с помощью метода setIndex. См. Мой ответ для более подробной информации. – Wilt

3

В новейшей трех js-версии вы не можете установить индекс, как написал в своем ответе @ calvin-sydney. Вам нужно будет использовать метод setIndex от THREE.BufferGeometry.

geometry.addAttribute('uv', new THREE.BufferAttribute(new Float32Array(uvs), 2)); 
geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(positions), 3)); 
geometry.addAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3)); 
geometry.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3)); 

geometry.setIndex(new THREE.BufferAttribute(new Uint32Array(indices), 1));