将对象旋转到面向鼠标方向

时间:2015-04-27 18:23:18

标签: c# unity3d

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

我的主要轮换方法是:

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 ();

        }
    }

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

如何正确修改我的代码?

1 个答案:

答案 0 :(得分:1)

它只在您的鼠标停止时旋转,因为这是您告诉它旋转的唯一时间。在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); } } 。这意味着您只需在按下按钮时旋转船只。

您应该做的是接受鼠标事件并使用它来设置目标,然后继续向该目标旋转。例如,

$q = $_GET['q'];
header ("Location: http://www.oldURLL.com/results.php?" . $q . "");

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