Working with the coordinate system and game screen

2020-05-26 08:42发布

So I've developed games in other platforms where the x/y coordinate system made sense to me. The top left representing the game screen with coordinates of (0,0) and the bottom right was (width,height). Now I'm trying to make the jump to Unity 2d and I can't understand how the game screen works. If I had a background object and a character object on the screen, when I move the character around his x and y values vary between -3 and 3... very small coordinates and it doesn't match the game resolution I have setup (1024x768). Are there good tutorials for understanding the game grid in Unity? Or can anyone explain how I can accomplish what I'm trying to do?

2条回答
做自己的国王
2楼-- · 2020-05-26 09:27

There are three coordinates systems in Unity: Screen coordinates, view coordinates and the world coordinates.

World coordinates: Think of the absolute positioning of the objects in your scene, using "points". You can choose to have the units represent any length you want, for example 1 unit = 10 meters. What is actually shown on the screen is determined by where the camera is placed and how it is oriented.

View Coordinates: The coordinates in the viewport of a given camera. Viewport is the imaginary rectangle through which the world is viewed. These coordinates are porportional, and range from (0,0) to (1,1).

Screen Coordinates: The actual pixel coordinates denoting the position on the device's screen.

Note that the world co-ordinates of any given object will always be the same regardless of which camera is used to view, whereas the view coordinates depends on the camera being used. The screen coordinates in addition depend on the resolution of the device and the placement of the camera view on the screen.

The "Camera" object provides several methods to convert between these different coordinate systems like "ScreenToViewportPoint" "ScreenToWorldPoint" etc.

Example: Place object on top left of screen

    float distanceFromCamera = 10.0f;
    Vector3 pos = Camera.main.ScreenToWorldPoint (new Vector3 (0, Screen.height, distanceFromCamera));

    transform.position = pos;

The ScreenToWorldPoint function takes a Vector3 as an argument, where the x and y denote the pixel position on the screen ( 0,0 is the bottom left) and the z component denotes the desired distance from the camera. An infinite number of 3D locations can map to the same screen position, so you need to provide this value.

Just make sure that the desired position falls within the clipping region of the camera. Also, you might need to pick a proper pivot for your object depending on which part of your object you want centered on the top left.

查看更多
Emotional °昔
3楼-- · 2020-05-26 09:29

Using:

Camera.main.WorldToScreenPoint (transform.position);

Let's me convert my GameObjects tranform position to the screen's x and y coordinate system

查看更多
登录 后发表回答