Simple square using BufferGeometry

Viewed 329

I used to have a custom square in my project that was made by using THREE.Geometry. Now after the latest update of three.js, Geometry was completely deleted and I have to get my code to work with BufferGeometry instead. I'm kind of confused how I have to change the code to make it work. I don't really get the vertices part now. I used to have 4 vertices made of Vector3's and two faces.

So it looked like that:

let v1 = new THREE.Vector3(...,...,...)
let v2 = new THREE.Vector3(...,...,...)
let v3 = new THREE.Vector3(...,...,...)
let v4 = new THREE.Vector3(...,...,...)

obj.vertices.push(v1)
obj.vertices.push(v2)
obj.vertices.push(v3)
obj.vertices.push(v4)

let face1 = new THREE.Face3(0, 1, 2)
let face2 = new THREE.Face3(2, 3, 0)

obj.faces.push(face1)
obj.faces.push(face2)

I've read the documentation on that on the THREE website but I don't really understand how I change that to make it work with BufferGeometry. Any tips would be appreciated.

Thanks

1 Answers

Try it like so:

let camera, scene, renderer;

init();
render();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.z = 2;

  scene = new THREE.Scene();

  const geometry = new THREE.BufferGeometry();

  const vertices = [
    -1, -1, 0,
    1, -1, 0,
    1, 1, 0,
    -1, 1, 0
  ];

  const indices = [
    0, 1, 2, // first triangle
    2, 3, 0 // second triangle
  ];

  geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
  geometry.setIndex(indices);

  const material = new THREE.MeshBasicMaterial();

  const mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

  renderer = new THREE.WebGLRenderer({antialias: true});
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

}

function render() {

  renderer.render(scene, camera);

}
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.126.1/build/three.js"></script>

Related