簡體   English   中英

旋轉對象使其面對鼠標方向

[英]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方法中調用此方法, 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 )中,您僅在Input.GetMouseButton(0)為true時調用RotateShip() 這意味着您僅在按下按鈕時才旋轉船。

您應該做的就是獲取該鼠標事件,並使用它來設置目標,然后朝該目標連續旋轉。 例如,

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)按下時進行旋轉,而且在更新中連續進行旋轉,而僅在單擊鼠標時設置目標點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM