-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTileMap2D.js
92 lines (80 loc) · 2.88 KB
/
TileMap2D.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import React, { useRef, useEffect } from "react";
import * as THREE from "three";
const TileMap2D = ({ mapData }) => {
const dummyObj = new THREE.Object3D();
const blackColor = new THREE.Color("black");
const greyColor = new THREE.Color("grey");
const yellowColor = new THREE.Color("yellow");
// const whiteColor = new THREE.Color("white");
const nrow = mapData.length;
const ncol = mapData[0].length;
const nrowSeg = Math.ceil(nrow / 100);
const ncolSeg = Math.ceil(ncol / 100);
console.log(`rows: ${nrowSeg} columns: ${ncolSeg}`);
// const nrowSeg = 2;
// const ncolSeg = 1;
const refs = [];
for (let i = 0; i < nrowSeg; i++) {
const t = [];
for (let j = 0; j < ncolSeg; j++) {
const tempRef = useRef();
t.push(tempRef);
}
refs.push(t);
}
useEffect(() => {
// set position & color
for (let rowSeg = 0; rowSeg < nrowSeg; rowSeg++) {
for (let colSeg = 0; colSeg < ncolSeg; colSeg++) {
const rowOffset = rowSeg * 100;
const colOffset = colSeg * 100;
const rowBoundary = rowSeg == nrowSeg - 1 ? nrow : rowOffset + 100;
const colBoundary = colSeg == ncolSeg - 1 ? ncol : colOffset + 100;
// const colBoundary = 100;
// console.log(`colBoundary: ${colBoundary} rowBoundary: ${rowBoundary}`);
let id = 0;
for (let i = rowOffset; i < rowBoundary; i++) {
for (let j = colOffset; j < colBoundary; j++) {
const tile = mapData[i][j];
const color =
tile == -1 ? blackColor : tile == 100 ? greyColor : yellowColor;
dummyObj.position.set(i * 0.1 - 9, j * 0.1 - 22, 0);
dummyObj.updateMatrix();
// const id = (i - rowOffset) * (rowBoundary - rowOffset) + (j - colOffset);
refs[rowSeg][colSeg].current.setMatrixAt(id, dummyObj.matrix);
refs[rowSeg][colSeg].current.setColorAt(id, color);
// refs[rowSeg][colSeg].current.material.needsUpdate = true;
id++;
}
}
}
}
}, [mapData]);
const instanceMeshes = [];
for (let i = 0; i < nrowSeg; i++) {
for (let j = 0; j < ncolSeg; j++) {
let nInstances = 100 * 100;
if (i == nrowSeg-1 && j == ncolSeg-1) {
nInstances = (nrow % 100) * (ncol % 100);
} else if (i == nrowSeg-1 && j != ncolSeg-1) {
nInstances = (nrow % 100) * 100;
} else if (i != nrowSeg-1 && j == ncolSeg-1) {
nInstances = 100 * (ncol % 100);
}
// console.log(`i: ${i}; j: ${j}; nInstances: ${nInstances};`);
const tempMesh = (
<instancedMesh
ref={refs[i][j]}
args={[null, null, nInstances]}
key={`${i}-${j}`}
>
<planeGeometry/>
<meshBasicMaterial />
</instancedMesh>
);
instanceMeshes.push(tempMesh);
}
}
return <>{instanceMeshes}</>;
};
export default TileMap2D;