unity將物體 旋轉指定角度


要實現這個功能,需要用四元數。你不用知道什么叫四元數,你只需要知道怎么用就行了。

例如每按一次空格,讓一個物體繞Y軸旋轉90度

 public float agle=90;
 private int n = 0;
 public float speed = 5;
// Update is called once per frame
void Update () {
     if (Input.GetKeyDown(KeyCode.Space))
     {
          ++n ;
      }
      transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(Vector3.up * (90 * n % 360)), Time.deltaTime * speed);
}

當然也可以使用
 Quaternion.Slerp(r1,r2,speed);
兩者的區別你可以在API中查看。

第二篇修改后
void Update () {
        //設置物體的旋轉為指定角度 (0-360)度 0-360這里是角度不是弧度
        //弧度與角度的關系是 弧度=弧長/半徑
        transform.rotation = Quaternion.Euler(Vector3.up * (yaw % 360));
        if (Input.GetKeyDown(KeyCode.A))
        {
            n++;
        }
        //按一次鍵盤 物體旋轉90度
        transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(Vector3.up * (90 * n % 360)), Time.deltaTime * speed);
}

 

end

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM