InstancedMesh getMatrixAt returning undefined

Hello

I am trying to interact with an object in an instancedMesh. I have set up an example here which uses react-three-fiber and a bit of drei but hopefully the principles are the same.

When I click on a cube, I want to get the information for that object, with the aim to then set the position of that cube to something different. However, when using getMatrixAt() it’s returning undefined.

I’ve seen a few examples, mainly here and another here but I can’t seem to get mine to work in a similar way.

My hunch is it’s something to do with the matrix value I’m passing through, but I’m not sure.

Any help on this would be greatly appreciated!

Please may I bump

Hi!

I can’t click on a cube, as I get this, running the first link you provided:

sigh Thanks for pointing this out to me. Mustn’t have saved. I’ll redo now and make sure to save!

ok, fingers crossed everything is sorted now - please let me know if you’re still having issues:

In the docs:
.getMatrixAt ( index : Integer, matrix : Matrix4 ) : undefined
It’s a method, that puts matrix data in the Matrix4 object, passed in the second parameter, and returns undefined.
If you do it this way:

  const handleClickEvent = (event) => {
    event.stopPropagation();
    const instanceId = event.instanceId;
    ref.current.getMatrixAt(instanceId, temp.matrix);
    console.log(temp.matrix);
  };

you’ll get an object of matrix in the console.

1 Like

Ah right, thank you. I hadn’t appreciated that it puts data into a Matrix object. Do you know how I can update the position of that object? Tbh I’m not the best with dealing with matrices. I’m going to do some digging now but thought I’d ask if you know off the top of your head?

Ah I might be part of the way there.:

    temp.matrix.setPosition(10,10,10)
    
    ref.current.setMatrixAt(event.instanceId, temp.matrix)
    ref.current.instanceMatrix.needsUpdate = true

I just need to find a way to extract the current position out of the matrix information of the clicked object

You can have an instance of Object3D and re-use it to decompose a matrix.

let tempObj = new THREE Object3D();

// in animation loop or anywhere else
mesh.getMatrixAt(i, matrix);
matrix.decompose(tempObj.position, tempObj.quaternion, tempObj.scale); // now position is in tempObj.position
1 Like

You are an absolute lifesaver. Thanks you @prisoner849 , that’s a massive, massive help. I completely didn’t appreciate that when we get these values we’re setting them to objects we pass in.

Thank you again!