/// <summary>
/// 获取鼠标点击坐标
/// </summary>
Vector3 screenPosition;//将物体从世界坐标转换为屏幕坐标
Vector3 mousePositionOnScreen;//获取到点击屏幕的屏幕坐标
Vector3 mousePositionInWorld;//将点击屏幕的屏幕坐标转换为世界坐标
public Vector3 MouseFollow()
{
//获取鼠标在相机中(世界中)的位置,转换为屏幕坐标;
screenPosition = Camera.main.WorldToScreenPoint(transform.position);
//获取鼠标在场景中坐标
mousePositionOnScreen = Input.mousePosition;
//让场景中的Z=鼠标坐标的Z
mousePositionOnScreen.z = screenPosition.z;
//将相机中的坐标转化为世界坐标
mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePositionOnScreen);
//物体跟随鼠标移动
//transform.position = mousePositionInWorld;
//物体跟随鼠标X轴移动
return new Vector3(mousePositionInWorld.x, mousePositionInWorld.y, mousePositionInWorld.z);
}
Unity中获取鼠标点击转换
最新推荐文章于 2024-06-24 18:11:55 发布