Unity跟delphi比起来太难了。在 Delphi 中你可以说:
Rectangle1.Position.Y := 0;
Rectangle1.Position.X := screen.Width - Rectangle1.Width;
这只会将矩形的位置更改为屏幕的右上角。但是在 Unity 中,仅仅为了做到这一点就需要学习很多东西,我不知道从哪里开始。有人可以给我简化一下吗?我只想在智能手机和个人电脑的屏幕右上角创建一个对象。
我正在使用 Unity2D
编辑:这是我要创建的对象的检查器:
这是我用来在屏幕上创建对象的代码:
Instantiate(objectName, new Vector3(0, 0, 0), Quaternion.identity);
编辑更清楚:
相机的屏幕坐标与世界坐标不同(一个有 2 个维度,另一个有 3 个维度。一个使用像素,另一个使用 Unity 单位)。
我会使用 Camera.ScreenToWorldPoint .
引用文档:
Camera.ScreenToWorldPoint(position: Vector3) Transforms position from screen space into world space.
Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.
因此,以与您描述的方式类似的方式(使用伪代码 C# 混合)将 Rectangle 放在角落:
Vector3 p = camera.ScreenToWorldPoint(new Vector3(0, Screen.height, HowFarFromCamera));
Rectangle1.position = new Vector3(p.x + Rectangle1.Width/2,p.y - Rectangle1.Height/2,p.z);
Point p 是世界坐标中的角点(这很重要)。假设您的矩形的轴心位于中间,我移动了 Width/2 和 Height/2。
注意:您可以使用Bounds.size获取宽度或高度(可用于渲染器和 SpriteRenderer 的结构)