因此,在我的Unity练习中,我必须旋转一个GameObject,使其远离我单击鼠标的位置。此外,我只能绕Y轴旋转,即GameObject只能完全向右或完全向左旋转,并且不能在任何点朝地面倾斜。此外,我必须在没有RayCasting的情况下完成这项工作(我已经用RayCasting完成了这项工作,所以作为练习,我必须在没有RayCasting的情况下完成)。以下是我多次尝试后编写的代码,但似乎效果不够好:
Vector3 clickLocation = Input.mousePosition;
Vector3 clickWorldLocation = Camera.main.ScreenToWorldPoint(new Vector3(clickLocation.x, clickLocation.y, transform.position.x)); //the transform.position.x is just to add some depth
transform.LookAt(new Vector3(clickWorldLocation.x, transform.position.y, clickWorldLocation.z), Vector3.up);如果我的GameObject保持在其起始位置,则此代码运行良好,但如果我将其移动到另一个位置并尝试相同的操作,则此代码将失败。有谁能帮帮我吗?
发布于 2020-02-15 02:21:05
首先,尽可能不频繁地调用Camera.main,如it uses an expensive operation (FindGameObjectsWithTag),并且不缓存结果。
private Camera mainCamera;
void Awake()
{
mainCamera = Camera.main;
}要回答您的问题,请不要在这种情况下使用ScreenToWorldPoint,因为深度不是最容易计算的。对于z组件,您没有任何有意义的东西可用,transform.position.x在这里也没有意义。
而是创建要单击的Plane (例如,平行于视图平面并与对象相交的平面),使用ScreenPointToRay将鼠标位置转换为Ray,然后查找光线和平面相交的位置。Plane.Raycast 比物理光线投射快得多。然后,找到从鼠标世界位置到对象的方向,并使用Quaternion.LookRotation将该方向转换为可以指定给对象旋转的旋转:
Ray mouseRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane mousePlane = new Plane(mainCamera.transform.forward, transform.position);
float rayDistance;
if (mousePlane.Raycast(mouseRay, out rayDistance))
{
Vector3 mouseWorldPos = mouseRay.GetPoint(rayDistance);
// make the z component of mouseWorldPos the same as transform.position
mouseWorldPos.z = transform.position.z;
Vector3 awayFromMouseDir = transform.position - mouseWorldPos;
transform.rotation = Quaternion.LookRotation(awayFromMouseDir, Vector3.up);
}https://stackoverflow.com/questions/60231328
复制相似问题