if (Input.GetKeyDown(KeyCode.A)) //按下A键
{
print("子物体的本地坐标: " + s.localPosition);
print("子物体的世界坐标: " + s.position);
print("世界转本地: " + p.InverseTransformPoint(s.position));
}
public Transform cube; //将Cube拖进去
public Text text; //将Text拖进去
void Update()
{
//获取Cube顶上的位置的世界坐标
Vector3 pos = cube.position + Vector3.up;
//将该世界坐标转为屏幕坐标赋给Text
text.transform.position = Camera.main.WorldToScreenPoint(pos);
}
世界坐标在转屏幕坐标时会忽略Z轴信息,因为屏幕坐标没有Z轴。
●屏幕转世界:Camera.main.ScreenToWoldPoint
public Transform cube; //方块
public Transform mainCamera; //主摄像机
void Update()
{
if (Input.GetMouseButton(0)) //按住鼠标左键
{
//获取鼠标屏幕坐标(Z轴为0)
Vector3 mPos = Input.mousePosition;
//以摄像机z轴为法线创建摄像机XY轴组成的平面
Plane pla = new Plane(mainCamera.forward, mainCamera.position);
//获取该物体到平面的距离(z轴垂直距离)
float dis = pla.GetDistanceToPoint(cube.position);
//将屏幕坐标转为世界坐标
cube.position = Camera.main.ScreenToWorldPoint(new Vector3(mPos.x, mPos.y, dis));
}
}
public Text text; //显示视口坐标
public Text text1; //显示比例
void Update()
{
//获取鼠标坐标的屏幕坐标
Vector2 mouPos = Input.mousePosition;
//将屏幕坐标转为视口坐标
Vector2 viewPos = Camera.main.ScreenToViewportPoint(mouPos);
//显示视口坐标(保留小数点后两位)
text.text = "视口: " + viewPos.ToString("0.00");
//获取屏幕坐标与屏幕的宽高比
float x = mouPos.x / Screen.width;
float y = mouPos.y / Screen.height;
Vector2 viewpos1 = new Vector2(x, y);
//显示比例
text1.text = "比值: " + viewpos1.ToString("0.00");
}
public Text text; //显示视口坐标
public Text text1; //显示比例
void Update()
{
//获取鼠标坐标的屏幕坐标
Vector2 mouPos = Input.mousePosition;
//直接显示屏幕坐标
text.text = "直接显示屏幕坐标: " + mouPos.ToString();
//获取屏幕坐标与屏幕的宽高比
float x = mouPos.x / Screen.width;
float y = mouPos.y / Screen.height;
Vector2 viewpos = new Vector2(x, y);
//将视口坐标转为屏幕坐标
Vector2 mouPos1 = Camera.main.ViewportToScreenPoint(viewpos);
text1.text = "转换后的屏幕坐标: " + mouPos1.ToString();
}
原文:https://www.cnblogs.com/howie-cn/p/13634504.html