旋转对象以面向鼠标方向

Rotate object to face mouse direction

我有一个方法可以将我的对象旋转到鼠标刚刚单击的位置。但是,只要按住鼠标按钮,我的对象就会旋转。

我主要的旋转方法是这样的:

void RotateShip ()
{
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    Debug.Log (Input.mousePosition.ToString ());
    Plane playerPlane = new Plane (Vector3.up, transform.position);

    float hitdist = 0.0f;

    if (playerPlane.Raycast (ray, out hitdist))
    {
        Vector3 targetPoint = ray.GetPoint (hitdist);
        Quaternion targetRotation = Quaternion.LookRotation (targetPoint - transform.position);
        transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, speed * Time.deltaTime);
    }
}

我在 FixedUpdate 方法中调用此方法,并将其包装在以下 if 语句中:

void FixedUpdate ()
    {
        // Generate a plane that intersects the transform's position with an upwards normal.


        // Generate a ray from the cursor position
        if (Input.GetMouseButton (0)) 
        {

            RotateShip ();

        }
    }

但是,只要按住鼠标按钮,对象仍然只会旋转。我希望我的对象继续旋转到我的鼠标刚刚单击的点,直到它到达该点。

如何正确修改我的代码?

它只会在您按下鼠标时旋转,因为那是您唯一让它旋转的时间。在您的 FixedUpdate(Imtiaj 正确地指出应该是 Update)中,您只调用了 RotateShip()Input.GetMouseButton(0) 为真。这意味着您只能在按下按钮时旋转您的飞船。

你应该做的是获取那个鼠标事件并用它来设置一个目标,然后不断地向那个目标旋转。例如,

void Update() {    
    if (Input.GetMouseButtonDown (0)) //we only want to begin this process on the initial click, as Imtiaj noted
    {

        ChangeRotationTarget();

    }
    Quaternion targetRotation = Quaternion.LookRotation (this.targetPoint - transform.position);
    transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, speed * Time.deltaTime);
}


void ChangeRotationTarget()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    Plane playerPlane = new Plane (Vector3.up, transform.position);

    float hitdist = 0.0f;

    if (playerPlane.Raycast (ray, out hitdist))
    {
        this.targetPoint = ray.GetPoint (hitdist);
    }
}

所以现在我们不再只在 MouseButton(0) 按下时进行旋转,而是在更新中连续进行旋转,而不是仅在单击鼠标时设置目标点。