All mesh instances reset to (0,0,0) before they lerp to new position when count changes

Hi everyone!

I am currently working on my graduation project in which mesh instances are re positioned over time. Besides the positions of the instances, the count of the mesh instances can also change over time.

Based on the following code examples, I managed to build this functionality.

https://threejs.org/examples/?q=dynami#webgl_instancing_dynamic

However, the problem appears when I want to lerp the positions of the instances. The position of all instances is resets to (0,0,0) when the count of the mesh instances changes.

I’ve created a codesandbox that reproduces this. The code has been forked from Instanced Mesh Lerping Positions - CodeSandbox by James Wesc and tweaked a bit to clarify the issue.

My problem appears when you change the count of the instances by dragging the slider. The position of all instances is resets to (0,0,0).

Is there a way to stop the reset and only update the new instances when the count changes?

This is a link to the code sandbox.

I added a snippet to the code as well!

Thanks in advance!!

const tempObject = new Object3D();
const tempMatrix = new Matrix4();
const tempVector = new Vector3();
const tempVector2 = new Vector3();

type XYZ = [number, number, number];

const data = dataJSON as Array<{ p1: XYZ; p2: XYZ }>;

const pos = new Vector3(10, 1, 1);

const YourCanvas = withControls(Canvas);

const Boxes: React.FC = () => {
  const count = useControl("count", {
    type: "number",
    value: 1000,
    min: 100,
    max: 1000,
    distance: 0.1
  });
  const ref = useRef<InstancedMesh>(null!);

  React.useEffect(() => {
    if (ref.current) {
      ref.current.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
    }
  }, []);

  useFrame(({ clock: { elapsedTime } }) => {
    const t = Math.floor(elapsedTime / 5) % 2;
    for (let i = 0; i < count; i++) {
      ref.current.getMatrixAt(i, tempMatrix);
      tempVector.setFromMatrixPosition(tempMatrix);

      const toPosition = t ? data[i].p1 : data[i].p2;

      // Resets positions of all instances when count changes
      // tempVector2.set(toPosition[0], toPosition[1], toPosition[2])
      // tempObject.position.lerpVectors(tempVector, tempVector2, 0.01)

      // Only updating positions of new instances when count changes
      tempObject.position.set(toPosition[0], toPosition[1], toPosition[2]);

      tempObject.updateMatrix();
      ref.current.setMatrixAt(i, tempObject.matrix);
    }
    ref.current.instanceMatrix.needsUpdate = true;
  });

  return (
    <instancedMesh
      ref={ref}
      args={[
        new THREE.BoxGeometry(1.0, 1.0, 1.0, 1.0),
        new THREE.MeshStandardMaterial({ color: new THREE.Color("#00ff00") }),
        count
      ]}
    ></instancedMesh>
  );
};