雖然transform.Rotate() 可以旋轉物體,但一旦旋後x,y,z的軸就會跑掉,沒辦法持續作出垂直或平行於地平線的旋轉。

方法之一就是放一個外殼,每當外殼完成一次旋轉後座標歸零,但裡面的東西不歸零。

子物件在旋轉時transform.localRotation 和 transform.rotation(世界作標) 是分開計算的,可以用這個方法記錄被外殼帶的作標,外殼歸零時不會

但是這個作法在歸零的一瞬間子物件會同時接收到外殼歸零的座標和自已的world rotation的座標,因此會先回到歸零的角度再回到自已原本的角度,會有一瞬間抖一下的感覺

 

在視覺上完美的作法為 : 要旋轉時才將外殼當成母物件,語法 :  transform.SetParent(shell.transform);

然後旋轉完畢時,再跳出外殼,語法 : transform.parent = null,就不會受到外殼歸零時的影響。

 

結果 : 

怎麼轉都平行或垂直於螢幕

 

殼的代碼 ; 

using UnityEngine;
using System.Collections;

public class shellRotation : MonoBehaviour {

  
    float yValue = 0;
    float xValue = 0;
    public bool childMove = false;

    GameObject Cube;
    boxRotation boxRotation;

    // Use this for initialization
    void Start () {

    }
    
    // Update is called once per frame
    void Update () {

        rotate();


    }

    void rotate()
    {

        if (Input.GetKey(KeyCode.A))
        {
            yValue += 2;
            childMove = true; 
        }
    


        if (Input.GetKey(KeyCode.D))
        {
            yValue -= 2;
            childMove = true;
        }


        if (Input.GetKey(KeyCode.W))
        {
            xValue += 2;
            childMove = true;
        }
   

        if (Input.GetKey(KeyCode.S))
        {
            xValue -= 2;

            childMove = true;
        }


        transform.rotation = Quaternion.Euler(xValue, yValue, 0);
        if (yValue < 0) { yValue += 360; }
        if (yValue >= 360) { yValue -= 360; }
        if (xValue < 0) { xValue += 360; }
        if (xValue >= 360) { xValue -= 360; }

        if (Input.GetKeyUp(KeyCode.S) || Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D) || Input.GetKeyUp(KeyCode.W))
        {
            childMove = false;
            xValue = 0;
            yValue = 0;
        }
    }
}
 

 

被旋轉物體的代碼 : 

 

using UnityEngine;
using System.Collections;

public class boxRotation : MonoBehaviour {

    GameObject shell;
    shellRotation shellRotation;
    Quaternion worldRot; 

    // Use this for initialization
    void Start () {
        shell = GameObject.Find("shell");
        shellRotation = shell.GetComponent<shellRotation>();
 

    }
    
    // Update is called once per frame
    void Update () {
    
    
        Debug.Log("transform.localrotation : " + transform.localRotation);
        if(shellRotation.childMove == true) {
            transform.SetParent(shell.transform);

        }
        if (shellRotation.childMove == false)
        {
            transform.parent = null;
        }

    }

}
 

 

 

arrow
arrow
    全站熱搜

    Yoda2016 發表在 痞客邦 留言(0) 人氣()