Hi!
I’m currently working on creating a terrain using DynamicTerrain, and so far, I haven’t encountered any problems. However, I’m trying to modify the mapData based on mouse clicks, and there’s something I’m not getting (or using incorrectly) because my clicks are not translated to the correct index, which results in modifying a different location on the map.
I get the cursor position this way :
scene.onPointerDown = (evt, pickResult) => {
if (pickResult.hit) {
const pickedPoint = pickResult.pickedPoint;
const x = Math.floor(pickedPoint.x);
const z = Math.floor(pickedPoint.z);
this.mapManager.modifyTerrainAtPoint(x, z, 1);
}
};
DynamicTerrain is “created” this way :
const mapData = new Float32Array(this.mapSubX * this.mapSubZ * 3);
for (let l = 0; l < this.mapSubZ; l++) {
for (let w = 0; w < this.mapSubX; w++) {
const x = (w - this.mapSubX * 0.5) * 2.0;
const z = (l - this.mapSubZ * 0.5) * 2.0;
const y = 0;
const idx = 3 * (l * this.mapSubX + w);
mapData[idx] = x;
mapData[idx + 1] = y;
mapData[idx + 2] = z;
}
}
And modifyTerrainAtPoint is like that :
modifyTerrainAtPoint(x, z, deltaHeight) {
x -= this.terrain.mesh.position.x;
z -= this.terrain.mesh.position.z;
let mapSizeX = this.terrain._terrainSizeX;
let mapSizeZ = this.terrain._terrainSizeZ;
let mapSubX = this.terrain._mapSubX;
let mapSubZ = this.terrain._mapSubZ;
let normalizedX = (x + mapSizeX / 2) / 2.0;
let normalizedZ = (z + mapSizeZ / 2) / 2.0;
let col = Math.floor((normalizedX / mapSizeX) * mapSubX);
let row = Math.floor((normalizedZ / mapSizeZ) * mapSubZ);
col = Math.max(0, Math.min(col, mapSubX - 1));
row = Math.max(0, Math.min(row, mapSubZ - 1));
let index = 3 * (row * mapSubX + col) + 1;
this.terrain.mapData[index] += deltaHeight;
this.terrain.update();
}
I’m not sure if there’s a simpler way or a method available in DynamicTerrain to achieve this, or if my calculation is completely incorrect. However, after multiple attempts, there’s still an inconsistency between the click and the modification index…
Thanks in advance for any help or guidance!