Estoy tratando de hacer un cubo giratorio en 3D, pero el cubo tiene una forma extraña, no puedo encontrar el error/falla.
Estoy siguiendo este tutorial en youtube. Creo que hice algo mal en mi código, pero todo me parece bien y verifiqué los valores en el modo de depuración de Chrome.
Pero cuando sigo el tutorial, realizo algunos cambios personales, pero estoy seguro de que estos cambios no afectan el funcionamiento del código y hacen que la optimización funcione.
Gracias.
const canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'); const W = 600, H = 600; const MODEL_MAX_X = 2, MODEL_MIN_X = -2, MODEL_MAX_Y = 2, MODEL_MIN_Y = -2, STEP = 0.5; var points = [], triangles = []; for (let x = -1; x <= 1; x += STEP) for (let y = -1; y <= 1; y += STEP) for (let z = -1; z <= 1; z += STEP) points.push([x, y, z]); for (let dimension = 0; dimension <= 2; ++dimension) for (let side = -1; side <= 1; side += 2) { var sidePoints = points.filter(point => point[dimension] == side).slice(0,3); triangles.push([...sidePoints]); } function persvectiveProjection([x, y, z]) { return [x / (z + 4), y / (z + 4)]; } function project(point) { const [x, y] = persvectiveProjection(point); return [ W * (x - MODEL_MIN_X) / (MODEL_MAX_X - MODEL_MIN_X), H * (1 - y - MODEL_MIN_Y) / (MODEL_MAX_Y - MODEL_MIN_Y) ]; } ctx.lineWidth = 4; ctx.strokeStyle = '#000'; function renderPoint(point) { const [x, y] = project(point); ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + 1, y + 1); ctx.stroke(); } function renderTriangle (triangle) { const projectedTriangle = triangle.map(project); const [a, b, c] = projectedTriangle; ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.lineTo(c[0], c[1]); ctx.lineTo(a[0], a[1]); ctx.stroke(); } function rotateY(point, theta) { const [x, y, z] = point; return [ Math.cos(theta) * x - Math.sin(theta) * z, y, Math.sin(theta) * x + Math.cos(theta) * z ] } function rotateX(point, theta) { const [x, y, z] = point; return [ x, Math.cos(theta) * y - Math.sin(theta) * z, Math.sin(theta) * y + Math.cos(theta) * z ] } var theta = 0; var dtheta = 0.01; function render() { ctx.clearRect(0, 0, W, H); theta += dtheta; triangles.forEach(triangle => { var rotatedTriangle = triangle.map(point => rotateX(rotateY(point, theta), 0.43 * theta)); renderTriangle(rotatedTriangle); }) requestAnimationFrame(render); } render();