學(xué)習(xí)Unity(4)運(yùn)動(dòng)實(shí)例學(xué)習(xí)——模擬太陽(yáng)系

先上結(jié)果圖:


結(jié)果圖片

行星代碼

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class planet : MonoBehaviour {
    public Transform center;  // 太陽(yáng)
    public float distance;  // 公轉(zhuǎn)半徑
    public float normal_x;  // 方便在inspector窗口中指定法線(xiàn)
    public float normal_y;
    public float normal_z;
    public float speed;  // 角速度

    private Vector3 normal;  //  法線(xiàn)

    void Start () {
        transform.position = center.position + new Vector3 (distance, 0, 0);  // 初始化行星位置
        normal = new Vector3 (normal_x, normal_y, normal_z);
    }

    void Update () {
        transform.RotateAround (center.position, normal, speed * Time.deltaTime);
    }
}

行星的代碼比較簡(jiǎn)單。這里只說(shuō)明一下transform.RotateAround只適用于center.position靜止不動(dòng)的情況,或者中心是公轉(zhuǎn)者的父對(duì)象的情況,否則公轉(zhuǎn)者的軌道會(huì)非常奇怪。(你可以嘗試使用transform.RotateAround再制作一個(gè)月球繞地球轉(zhuǎn),地球繞太陽(yáng)轉(zhuǎn)的例子,地球不作為月球的父對(duì)象,當(dāng)你將地球的公轉(zhuǎn)速度設(shè)置得很快的時(shí)候,月球會(huì)出現(xiàn)“跟不上”地球的情況?。?/p>


衛(wèi)星代碼

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moon : MonoBehaviour {
    public Transform center;  // 地球
    public float distance;  // 地月距離
    public float normal_x;
    public float normal_y;
    public float normal_z;
    public float speed;

    private Vector3 normal;  // 法線(xiàn)

    private GameObject shadow;  // 地球的影子空對(duì)象

    void Start () {
        shadow = new GameObject ();
        shadow.transform.position = center.position;
        transform.parent = shadow.transform;  // 月球是影子地球的子對(duì)象
        transform.localPosition = new Vector3 (distance, 0, 0);  // 設(shè)置月球相對(duì)于影子地球的距離

        normal = new Vector3 (normal_x, normal_y, normal_z);
    }

    void Update () {
        shadow.transform.position = center.position;  // 時(shí)刻保持影子對(duì)象與地球同步
        shadow.transform.Rotate (normal, speed*Time.deltaTime);  // 影子對(duì)象自轉(zhuǎn),月球就會(huì)跟著旋轉(zhuǎn)。
    }
}

將月球設(shè)置為影子地球的子對(duì)象以后,月球與影子地球的相對(duì)方位就不會(huì)變化了,所以影子對(duì)象自轉(zhuǎn),就會(huì)使得月球繞著它公轉(zhuǎn)。


創(chuàng)建幾個(gè)球體,布置好位置和大小,將以上幾個(gè)代碼分別掛載到行星和衛(wèi)星上,設(shè)置一下各種public參數(shù),就可以運(yùn)行了。

注意如果初始狀態(tài),如果行星與太陽(yáng)的連線(xiàn)不與法線(xiàn)垂直,行星就不會(huì)繞著太陽(yáng)的中心旋轉(zhuǎn),而是:

行星初始位置與法線(xiàn)

造成這個(gè)問(wèn)題的根本原因是transform.Rotate是繞一條軸線(xiàn)旋轉(zhuǎn)的,第一個(gè)參數(shù)指定軸線(xiàn)上的一個(gè)點(diǎn),第二個(gè)參數(shù)指定軸線(xiàn)的方向,兩者共同確定一條軸線(xiàn)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容