簡體   English   中英

禁用Unity 5 2D中的對角線運動? (使用C#)

[英]Disabling diagonal movement in Unity 5 2D? (using C#)

或更確切地說,我應該說“有效地禁用對角線運動”。

在線上有很多Q / A,但是我一直遇到相同的問題:水平移動(例如,向左)時,我可以覆蓋當前方向並開始垂直移動(通過向上推),這是我想要的。 但這反過來是行不通的! 垂直運動不能替代水平運動。

void Update () {

         float h = Input.GetAxis("Horizontal");
         float v = Input.GetAxis("Vertical");
          ManageMovement(h, v); 
}    

void ManageMovement(float horizontal,float vertical) {

        if (vertical != 0f) {
                horizontal = 0f;
                Vector3 movement = new Vector3 (horizontal, vertical, 0);
                GetComponent<Rigidbody2D> ().velocity = movement * speed;
                return;
            } 

        if (horizontal != 0f) {
            vertical = 0f;
            Vector3 movement = new Vector3 (horizontal, vertical, 0);
            GetComponent<Rigidbody2D> ().velocity = movement * speed;
            return;

        } else {
            Vector3 noMovement = new Vector3 (0, 0, 0);
            GetComponent<Rigidbody2D> ().velocity = noMovement;
        }
    }

如果我顛倒了這些if()語句的順序,那么就可以解決問題。 所以,這是一個線索。 但是我不是一個偉大的偵探。 我希望有幫助!

使用輸入。 GetAxisRaw而不是GetAxis。

GetAxis以-1到1的比例返回浮點數。返回到0的速度取決於軸設置。 如果將重力設置為非常高的數字,它將更快地返回到0。 如果將靈敏度設置為很高的數值,它將更快地變為-1或1。

因此,根據這些設置,您的函數ManageMovement將被調用多次,並逐漸改變水平和垂直值。

隨着時間的推移,輸入內容可能如下所示:

Update #1: ManageMovement(0.2, 1.0)
Update #2: ManageMovement(0.3, 0.9)
...
Update #N: ManageMovement(1.0, 0.0)

因此,當您檢查vertical!= 0時,它將保持非零,直到它實際達到0,然后再將所有這些更新設置為horizo​​ntal為0。

GetAxisRaw不會以這種方式進行平滑。

嘗試將else語句添加到ManageMovement方法:

void ManageMovement(float horizontal,float vertical) {

    if (vertical != 0f) {
            horizontal = 0f;
            Vector3 movement = new Vector3 (horizontal, vertical, 0);
            GetComponent<Rigidbody2D> ().velocity = movement * speed;
            return;
        } 

    else if (horizontal != 0f) {
        vertical = 0f;
        Vector3 movement = new Vector3 (horizontal, vertical, 0);
        GetComponent<Rigidbody2D> ().velocity = movement * speed;
        return;

    } else {
        Vector3 noMovement = new Vector3 (0, 0, 0);
        GetComponent<Rigidbody2D> ().velocity = noMovement;
    }
}

暫無
暫無

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

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