- Home /
How to transform points from world to camera space and back again.
I am trying to find the screenspace bounds of an object so that I can draw a box around it. I don't think I can use a canvas or any other GUI method because I want the box to be occluded by other objects if the target object goes behind them. I also want to be able to use this with a skinnedmeshrenderer so standard bounding boxes wont work. I am currently projecting the vertex array from the mesh into the camera space like this:
Camera cam = Camera.main;
while (i < vertices.Length){
vertices[i] = cam.WorldToScreenPoint(vertices[i]);
i++;
}
I then find the screenspace max and min points which I place in a Vector3 List screenMinMaxList then transform them back into world space (and add in an animation transform) like this:
for (i = 0; i < screenMinMaxList.Count; i++) {
Vector3 temp = screenMinMaxList[i];
temp = cam.ScreenToWorldPoint (temp);
temp += trans.position;
screenMinMaxList[i] = temp;
}
I then draw a rectangle using the min and max X and Y values at a constant depth from the camera. The rectangle is way too small.
Answer by SunnyChow · Aug 10, 2017 at 05:11 AM
when you use ScreenToWorldPoint, the z value of input Vector3 is the distance. You should try setting it bigger. it will be the best if you set it as the distance bewteen camera and the selected object
Thanks for the suggestion. The error is certainly related to the depth and it is exacerbated by the depth variation of the object itself. If there is a lot of depth in screenspace, using a single value will always produce some error. I have modified the script to use the average depth right now and that is a lot better but not perfect.