[英]How can to position objects correctly in different resolutions in Unity?
I'm writing an Android game and as I wanted it to be played in portrait mode I want the scale of the objects to remain the same in regards to the screen width.我正在编写一个 Android 游戏,因为我希望它以纵向模式播放,所以我希望对象的比例在屏幕宽度方面保持不变。 I think I managed to do that with this code:
我想我设法用这段代码做到了:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Android;
public class PowerPosition : MonoBehaviour
{
void Start()
{
float w = Screen.width;
float h = Screen.height;
Vector2 position = (Camera.main.ScreenToWorldPoint(new Vector2(w * 0.9f, w * 0.53f)));
float ratio = (w / h) / (9f / 16f);
gameObject.transform.position = new Vector3(position.x * ratio, position.y * ratio, 0);
gameObject.transform.localScale = new Vector3(gameObject.transform.localScale.x * ratio, gameObject.transform.localScale.y * ratio, gameObject.transform.localScale.z * ratio);
The issue is with the positioning.问题在于定位。 It changes and objects that should have relative distances from each other get messed up.
它会发生变化,并且应该彼此具有相对距离的对象会变得混乱。 Objects that should appear one above the other become too close and overlap.
应该出现在另一个之上的对象变得太近并且重叠。 The "position * ratio" was a test, it doesn't work well either with or without that.
“位置*比率”是一个测试,无论有没有它都不能很好地工作。 Here for example I had to items that I wanted to keep a consistent distance from the lower right end of the screen.
例如,在这里我必须要与屏幕右下端保持一致距离的项目。
How can you fix that?你怎么能解决这个问题?
You can use percentage calculation as orientationbase to scale.您可以使用百分比计算作为方向基础来进行缩放。 That represents a relational scaleability.
这代表了关系可扩展性。
There is a false friend in your mind.你心里有个假朋友。 The displays haves different dots per inch.
显示器每英寸有不同的点数。 Will say, this value may be included your calculation.
会说,这个值可能会包含在你的计算中。
I will try to explain it differently.我将尝试以不同的方式解释它。
A device has a screen resolution of X-axis, Y-axis, color depth and ppi / dpi.一台设备的屏幕分辨率为 X 轴、Y 轴、色深和 ppi/dpi。
You can buy a display with 1920x1080xColors with 6 "or 32".您可以购买 1920x1080xColors 和 6" 或 32" 的显示器。 With large displays you have a lower pixel density compared to small displays.
与小型显示器相比,大型显示器的像素密度较低。
A device itself only changes X and Y if you have an orientation sensor.如果您有方向传感器,设备本身只会更改 X 和 Y。
Landscape 1920x1080 becomes portrait 1080x1920.横向 1920x1080 变为纵向 1080x1920。
When I take an iPhone, the display has a higher pixel density than the cheaper Android devices.当我拿 iPhone 时,显示器的像素密度比便宜的 Android 设备高。
In mathematics there is the famous three-sentence that is suitable for calculating proportions.数学上有著名的三句话,适用于计算比例。
You can query the value for the pixel density from the system.您可以从系统中查询像素密度的值。 You can use this value for rescaling your buttons.
您可以使用此值重新缩放按钮。
I work mostly with horizontal centering.我主要使用水平居中。 So I keep the symmetry.
所以我保持对称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.