How to scale gameobject to pixel width and height

Hi

I have an ortho camera and I want to position a game object at a fixed screen position top left of screen. I can use;

myGuiCamera.ScreenToWorldPoint(25, Screen.height - 25, 10)

And it positions it correctly, but… if the gameobject by default is too big, I want to scale it so that it will fit a certain pixel space.

Any thoughts on how this might be done?

Cheers

I guess the camera type is not really important, just the ability to get the x and y size in pixels, perhaps from the renderer component of a gameobject.

Display a GUI texture on screen as a guide, adjust the size of object by trial and error.

Thanks for the idea abbc. In the end I needed something a little more dynamic (I probably should have explained better).

I have most of what I want now with a solution like this; (c#)

Vector3 posStart = myCamera.WorldToScreenPoint(new Vector3(mesh.bounds.min.x, mesh.bounds.min.y, mesh.bounds.min.z));
Vector3 posEnd = myCamera.WorldToScreenPoint(new Vector3(mesh.bounds.max.x, mesh.bounds.max.y, mesh.bounds.min.z));

int widthX = (int)(posEnd.x - posStart.x);
int widthY = (int)(posEnd.y - posStart.y);

This gives me the width and height of the mesh in pixels.

I’ll use a similar method to convert the handle to screen coords so I know what offset I need when positioning it.

Cheers

1 Like

Maybe this is what you want.

Thanks abbc, that will help i think. I’ll need to work out how to convert the pixel size I want to the local scale.

Cheers

i would cast a ray with a certain length through both of the pixels. then you get the endpoints of the rays and can calculate the distance between them. then you can apply the formula linked above to calculate the required scale. then you could place the object in the mid between the two points.
what you should consider:
when the rays hit something you have a problem. maybe you should set the flags to exclude any layers.
when the object is not symmetrical you cant place it in the middle.
when the object should rotate you may want to use the axis aligned bounding box to determine the width.
the object still yould be occluded by stuff.

maybe consider using a second camera only rendering this object on top. this would help with the occlusion thing.

There are some good ideas in there, thanks exiguous, I’ll do some looking today and see how I go.

Cheers