Three.js simple rotating cube tutorial
HTML
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://threejs.org/examples/js/libs/dat.gui.min.js"></script>
CSS
body {
margin: 0;
overflow: hidden;
}
JavaScript
let raycaster, intersected;
const scene = new THREE.Scene();
const mouse = new THREE.Vector2();
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 300);
camera.position.set(2, 5, 3);
raycaster = new THREE.Raycaster();
let geometry = new THREE.BoxGeometry();
geometry = geometry.toNonIndexed(); // <======== CHANGED
const material = new THREE.MeshBasicMaterial( { vertexColors: true, color: new THREE.Color('white') } );
const mesh = new THREE.Mesh(geometry, material);
const positionAttribute = mesh.geometry.getAttribute('position');
const colors = [];
const color = new THREE.Color('white');
for (let i = 0; i < positionAttribute.count; i += 3) {
colors.push(color.r, color.g, color.b);
colors.push(color.r, color.g, color.b);
colors.push(color.r, color.g, color.b);
}
mesh.geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
scene.add(mesh);
const renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
document.addEventListener('mousemove', onPointerMove, false);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
const highlightFace = color => {
const { face } = intersected;
const colorAttribute = intersected.object.geometry.getAttribute('color');
colorAttribute.setXYZ(face.a, color.r, color.g, color.b);
colorAttribute.setXYZ(face.b, color.r, color.g, color.b);
colorAttribute.setXYZ(face.c, color.r, color.g, color.b);
offset = ( face.a % 2 == 0 ) ? 3 : - 3; // <======== CHANGED
colorAttribute.setXYZ(face.a + offset, color.r, color.g, color.b);
colorAttribute.setXYZ(face.b + offset, color.r, color.g, color.b);
colorAttribute.setXYZ(face.c + offset, color.r, color.g, color.b);
colorAttribute.needsUpdate = true;
};
function onPointerMove(event) {
event.preventDefault();
mouse.x =...