我需要将游戏对象的左上角与相机视图的左上角对齐。如何在Unity中将3D对象移动到屏幕的左上角?我无法弄清楚这一点,我找到的帖子都是在 Unity 2D 中。 谢谢您的帮助。
以下脚本将给定的
GameObject
移动到屏幕的左上角到相机的当前距离。如果需要的话可以改变。它根据对象相对于相机的渲染器范围来细化对象的位置:
public class SpawnScreenCorner : MonoBehaviour
{
[Tooltip("Main cam")]
private Camera mainCam;
[Tooltip("Gameobject to be aligned")]
public GameObject objToBeAligned;
// Start is called before the first frame update
void Start()
{
// Cache main camera
mainCam = Camera.main;
// Align obj to top left corner
AlignObj();
}
// Align object to top left corner of screen
public void AlignObj()
{
// Parent obj to camera temporarily
Transform prevParent = objToBeAligned.transform.parent;
objToBeAligned.transform.SetParent(mainCam.transform, false);
// Get the screen's top-left corner in screen coordinates at current distance (z) of object
Vector3 screenTopLeft = new Vector3(0, Screen.height, objToBeAligned.transform.localPosition.z);
// Convert the screen top-left corner to a world position
Vector3 worldTopLeft = mainCam.ScreenToWorldPoint(screenTopLeft);
// Adjust for the GameObject's size to align the top-left corner relative to camera space
Vector3 adjustedPosition = worldTopLeft + mainCam.transform.InverseTransformVector(new Vector3(objToBeAligned.GetComponent<Renderer>().bounds.extents.x, -objToBeAligned.GetComponent<Renderer>().bounds.extents.y, objToBeAligned.GetComponent<Renderer>().bounds.extents.z));
// Unparent object again
objToBeAligned.transform.SetParent(prevParent);
// Set the GameObject's position
objToBeAligned.transform.position = adjustedPosition;
}
}