I’m having trouble with understanding the Vector3 project method and exactly what NDC space is.
My understanding is that a Vector3 in NDC space is supposed to have all 3 coordinates in the range -1 to 1. So when I call vector.project(camera)
where vector
is a Vector3 and camera
is a PerspectiveCamera, the result should be a Vector3 which has x, y, and z coordinates all in the range -1 to 1.
The below code snippet is what I’m trying to use to project an object’s world position into screen coordinates. camera
is a PerspectiveCamera and object
is an Object3D.
camera.updateMatrixWorld();
camera.updateProjectionMatrix();
camera.updateWorldMatrix();
camera.updateMatrix();
object.updateMatrixWorld();
const width = window.innerWidth;
const height = window.innerHeight;
let pos = new THREE.Vector3();
pos = pos.setFromMatrixPosition(object.matrixWorld);
pos.project(camera);
pos.x = (pos.x + 1) * width / 2;
pos.y = -(pos.y - 1) * height / 2;
If I console.log()
the pos
variable just after calling pos.project(camera)
, I am getting values that look like nonsense. For an object that appears directly in the center of the scene on-screen, I’m getting values like pos.x = -1.10302...
and pos.y = 6.50278...
. For an object that appears in the center top of the screen, I’m getting values like pos.x = -2.03907...
and pos.y = 13.10969...
. Like I said above, my understanding of NDC space says these values should all be in the range -1 to 1, and an object directly in the center of the screen should have values pos.x = 0
and pos.y = 0
. So I don’t know if my understanding of NDC space is wrong, or if there’s something going wrong with the way I’m calling this method.
My final values for pos.x
and pos.y
are giving screen coordinates that are nowhere even close to mapping onto the Three.js objects on-screen, probably because of whatever is going wrong with my understanding of the Vector3.project
method. I don’t know what I’m doing wrong here, but I’ve read everything I can find about projecting vectors into screen space on StackOverflow and here and it’s all telling me to do pretty much what I’m doing here, but it’s not working. Notice that I am updating all of the matrices I can think of for both the camera
and the object
, so that shouldn’t be the issue like I’ve seen for some people with similar problems.
I’ve been beating my head against the wall about this for almost 3 whole days now and gotten nowhere. Am I missing something?
Happy to provide more clarification or code snippets on anything as necessary. Thanks!