- Home /
how to scale an object in order to fix the screen dimensions
Hi, in my script I instantiate a Game Object, in this case a PLANE.
The dimensions of the plane should be related to the screen size. So for example the plane's width should be half the screen's width.
I'm not an expert about the dimension of object, and the "scale" function is a bit tricky.
This is my code, really simple:
//window
window_position = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width + 120, Screen.height / 2, 10));
GameObject window= (GameObject)Instantiate(windowObject, window_position, Quaternion.Euler(-90, 0, 0));
*window.transform.localScale = new Vector3(4, 1, 6*);
Can you give me some hints, please?
Thanks, I really appreciate it! :)
What are you trying to do? It really depends on the distance to the plane, or is that what you want to change?
the GameObject i'm instantiating should be as wide as half of Screen Width...
Or in a more general way, how to relate the width of an object to the Width of the Screen currently running the game...
Answer by Hedayk · Nov 16, 2012 at 10:14 PM
I'm not exactly sure what you want but you should look into Screen.width and Screen.height .
Something like:
window.transform.localScale = Vector3(Screen.width/2,Screen.height/2,1);
Hope that helps.
I don't think this is going to work... I mean, you're comparing a Scale with a Dimension... they'are two differend measures...
I think you understood my question: i'd like to scale an object in order to fill exactly the Screen dimension.
Thanks
Answer by PaulUsul · Nov 17, 2012 at 10:52 AM
You need to look at the Camera class and all the different projection matrixs. cameraToWorldMatrix and worldToCameraMatrix
It is probably going to end up being some differential and harder math.
I would fake it with the use of camera.WorldToScreenPoint and the gameObjects bounds. I have made a small project as an example, with a plane and a camera.
this is the jist of it
// b = bounds, cam = camera
// LookAt gives a forward vector towards the object.
cam.transform.LookAt(b.center);
// This is the point we use to correct after.
point = cam.WorldToScreenPoint(go.transform.position + new Vector3(b.extents.x, 0, 0));
if (correct)
{
Vector3 newPosition = transform.position;
float screenCenter = Screen.width * 0.5f;
float halfScreenWidth = screenCenter * 0.5f + Screen.width * 0.5f;
// the plus 1 is so we don't jump back and forth.
if (point.x > halfScreenWidth + 1)
{
newPosition += -cam.transform.forward * Time.deltaTime * speed;
}
if (point.x < halfScreenWidth - 1)
{
newPosition += cam.transform.forward * Time.deltaTime * speed;
}
cam.transform.position = newPosition;
}
With regard to this question. Everyone wants to use the camera and every question involves scaling one object, not every object in the scene.