I have an object with multiple instances in my Three.js game:
const dummy = new THREE.Object3D();
const OBJECT_FILE_PATH = 'somefile.glb';
let objectGeometry,
objectMaterial,
objectMesh,
objectInstanceNumber = 150;
loader.load(
OBJECT_FILE_PATH,
function(gltf) {
const _objectMesh = gltf.scene.getObjectByName( 'objectName' );
objectGeometry = _objectMesh.geometry.clone();
const defaultTransform = new THREE.Matrix4()
.multiply( new THREE.Matrix4().makeScale( 1, 1, 1 ) );
objectGeometry.applyMatrix4( defaultTransform );
objectMaterial = _objectMesh.material;
objectMesh = new THREE.InstancedMesh( objectGeometry, objectMaterial, objectInstanceNumber );
objectMesh.castShadow = true;
objectMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
scene.add(objectMesh);
var zPos = -90;
var xPos = -90;
var gCounter = 0;
while(zPos <= 90) {
zPos += 3 + Math.floor(Math.random() * 6);
for ( let k = -1; k < 2; k++){
dummy.scale.setScalar( 0.2 + Math.floor(Math.random() * 4) / 10 );//setting random size 40-100%
dummy.rotation.y = Math.random() * Math.PI * 2;//random rotation
xPos = 60 * k - 30 + Math.floor(Math.random() * 60);//cell size: 60x60
dummy.position.set(
xPos,
0,
zPos + Math.floor(Math.random() * 5) / 10
);
dummy.updateMatrix();
objectMesh.setMatrixAt( gCounter, dummy.matrix );
gCounter++;
}
}
},
undefined, // We don't need this function
function(error) {
console.error(error);
}
);
I've placed all the objects where they should be within 9 hypothetical cells (each 60 x 60 unuts big) during initialization. But now, when a character moves, I need to move some objects from cells that are not visible anymore to new empty cells. How do I access those instances. What I need is to loop through the instances and move instances that have coordinates that I need. Something like
for(var i = 0; i < objectInstanceNumber; i++ ){
if(myInstances[i].position.x > -90 && myInstances[i].position.x < -30){
myInstances[i].position.x = 30 + Math.random() * 60;
}
}
Where myInstances would be an array of instances. Can anyone tell me how to do that, please? Thanks in advance.