import { BoxGeometry, Mesh, MeshBasicMaterial, Group } from 'three'; import { TextureLoader } from 'three/src/loaders/TextureLoader'; import { MotionEngine } from '../../lib/MotionEngine'; class PuzzleGame1 { constructor(context, image, w, h) { this.object = new Group(); const aq = new MotionEngine(); const pr = [[0, -1], [0, 1], [1, 0], [-1, 0], [0, 0], [0, 2]]; let d = 1.2; let bm = new BoxGeometry(1, 1, 1); let uv = bm.getAttribute('uv'); for (let i = 0; i < 6; i++) { let s = [(i % w) / w, (i % h) / h]; //top left uv.array[8 * i] = s[0]; uv.array[8 * i + 1] = s[1] + 1 / h; //top right uv.array[8 * i + 2] = s[0] + 1 / w; uv.array[8 * i + 3] = s[1] + 1 / h; //bottom left uv.array[8 * i + 4] = s[0]; uv.array[8 * i + 5] = s[1]; //bottom right uv.array[8 * i + 6] = s[0] + 1 / w; uv.array[8 * i + 7] = s[1]; } let material = new MeshBasicMaterial({ map: new TextureLoader().load(image) }); //material.map.encoding = sRGBEncoding; for (let i = 0; i < 6; i++) { let b = bm.clone(); let mesh = new Mesh(b, material); mesh.position.set((i % w) * d, (i % h) * d, 0); let ri; do { ri = Math.floor(Math.random() * 6); } while (ri == this.object.children.length); mesh.rotation.set(pr[ri][0] * Math.PI / 2, pr[ri][1] * Math.PI / 2, 0); mesh._ri = ri; this.object.add(mesh); } this.object.children[0].onBeforeRender = () => { this.update(); }; var check = () => { if (!this.object.children.length) return false; let i = 0; for (let c of this.object.children) { if (Math.abs(c.rotation.x - pr[i][0] * Math.PI / 2) > 0.0001 || Math.abs(c.rotation.y - pr[i][1] * Math.PI / 2) > 0.0001) return false; i++; } return true; }; let clickFn = (i) => { if (!this.done && !aq.isActive(i.object)) { i.object._ri = (i.object._ri + 1) % 6; aq.add({ o: i.object, a: { rotation: { x: pr[i.object._ri][0] * Math.PI / 2, y: pr[i.object._ri][1] * Math.PI / 2 } }, t: .5 }); } }; this.object.children.forEach(c => { context.clickable.add(c, clickFn); }); this.update = () => { aq.update(); if (aq.isIdle() && !this.done && check()) { this.done = true; this.object.children.forEach((c, i) => { aq.add({ o: c, a: { position: { x: i % w, y: i % h } }, t: 1, f: i == 0 && this.onfinish }); }); //context.dashboard.addPoints(10); } }; } } export { PuzzleGame1 }