Unity之繞軸進行旋轉

先上一張效果圖
這裏寫圖片描述

using UnityEngine;
using System.Collections;

public class TestRotateRound : MonoBehaviour
{
    public GameObject Sphere;
    private float curtTime = 0.0f;
    void Update()
    {
        //使用C#封裝好的代碼RotateAround
        gameObject.transform.RotateAround(Sphere.transform.position, Sphere.transform.up, 72 * Time.deltaTime);
        //自己封裝代碼,功能和上面的相同
        //RotateAround(Sphere.transform.position,Vector3.up, 72 * Time.deltaTime);
    }

    private void RotateAround(Vector3 center, Vector3 axis, float angle)
    {
        //繞axis軸旋轉angle角度
        Quaternion rotation = Quaternion.AngleAxis(angle, axis);
        //旋轉之前,以center爲起點,transform.position當前物體位置爲終點的向量.
        Vector3 beforeVector = transform.position - center;
        //四元數 * 向量(不能調換位置, 否則發生編譯錯誤)
        Vector3 afterVector = rotation * beforeVector;//旋轉後的向量
        //向量的終點 = 向量的起點 + 向量
        transform.position = afterVector + center;

        //看向Sphere,使Z軸指向Sphere
        transform.LookAt(Sphere.transform.position);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章