简体   繁体   中英

Position object on screen in different resolutions / aspect ratios (orthographic)

To be honest I am quite lost with world, screen and viewport coordinates in Unity.
My question is rather simple: in a 2d game how do I place an object in bottom left corner no matter what the resolution and screen aspect ratio is?

It is a little vague your description, but I think your talking about this:

Vector3 screenPos = new Vector3(x,y,z);

camera.ScreenToWorldPoint(screenPos);

As a side note, there are specific algorithms for 2D Unity, search for that also.

For Orthographic check this unity space which might help you:

http://answers.unity3d.com/questions/501893/calculating-2d-camera-bounds.html

I see no one ever followed up on this. Let's get some terms straight first: Camera.main = the main camera that is looking at your game world "game world" = the entire game map you've drawn World Point = an absolute, unique position in the game world. Can be 2D or 3D (x,y,z) Screen Point = a 2D x,y location of a pixel on the screen

So, when you want to place an object (ietransform its location) what you are really doing is placing it somewhere within the Game World. If the camera happens to be looking at that location in the World then it will appear on screen.

To figure out what parts of the World are currently on screen, you must convert a Screen Point to a World Point. So...assuming your object's size is 20x20, try this:

//Attach this script to the item you want "pinned" to the bottom, left corner of the screen
void Update() {
  //fetch the rectangle for the whole screen
  Rect viewportRect = Camera.main.pixelRect; //again, this has nothing to do with the World, just the 2D screen "size", basically

  //now, let's pick out a point on the screen - bottom, left corner - but leave room for the size of our 20x20 object
  Vector3 newPos = new Vector3(viewportRect.xMin + 20, Camera.main.pixelHeight - 20, 0);

  //now calculate where we need to place this item in the World so that it appears in our Camera's view (and, thus, the screen)
  this.transform.position = Camera.main.ScreenToWorldPoint(newPos);
}

I'm 98% certain this is all accurate info but if someone sees a mistake please point it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM