【问题标题】:Rotate object to face mouse direction旋转对象以面对鼠标方向
【发布时间】:2015-04-28 03:27:09
【问题描述】:

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

我的主要轮换方法是这样的:

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

        }
    }

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

如何正确修改我的代码?

【问题讨论】:

标签: c# unity3d


【解决方案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);
    }
}

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

【讨论】:

    猜你喜欢
    • 2018-10-23
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2013-05-25
    • 2013-11-04
    相关资源
    最近更新 更多