您的位置:首页 > 移动开发 > Unity3D

【Unity 3D游戏开发学习笔记】实现太阳系

2017-05-20 12:24 1076 查看

目标:

写一个程序,实现一个完整的太阳系, 其他星球围绕太阳的转速必须不一样,且不在一个法平面上。

基本思路是在里面创建对象,架构成一个太阳系,sun作为父对象,其他行星作为子对象,并且相对sun的初始位置均不一样,那么角速度相同的情况下转速就不一样了,另外法平面是采取随机分配一个方向给任意一个行星,只要y和z的比值不一样,那么就不会在同一个轨道上。

实现过程:

如图建立对象,并放到合适位置,改好名字



把脚本挂到Sun上,并给Script中的Transform对象赋值(把对应对象拉进去就行)



另外新建Material挂在星球上可以让星球看上去更好看,以下是地球的,图片网上搜的:





效果图:





我给太阳加了光源,让他能有照明的效果(在我的另一篇博客有对光源更多的介绍)



实现代码:

sunset.cs

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

public class sunset : MonoBehaviour {
public Transform sun;
public Transform mercury;
public Transform venus;
public Transform earth;
public Transform mars;
public Transform jupiter;
public Transform saturn;
public Transform uranus;
public Transform neptune;
public Transform moon;
// Use this for initialization
Vector3 []a = new Vector3[9];
float speed = 40;
float y, z;
void Start () {
int i = 0;
for (i = 0; i < 9; i++) {
y = Random.Range(1, 360); // 随机设置角度
z = Random.Range(1, 360); // 随机设置角度
a[i] = new Vector3(0, y, z); // 以上是为了制造不同的运动法平面,修改y和z可以使得绕不同的轴转
}
}

// Update is called once per frame
void Update () { // 每个星球的旋转动作,用到了初始化的a[i]
mercury.RotateAround(sun.position, a[0], speed*Time.deltaTime);
mercury.Rotate(Vector3.up *speed *Time.deltaTime);
venus.RotateAround(sun.position, a[1], speed*Time.deltaTime);
venus.Rotate(Vector3.up *speed *Time.deltaTime);
earth.RotateAround(sun.position, a[2], speed*Time.deltaTime);
earth.Rotate(Vector3.up *speed *Time.deltaTime);
mars.RotateAround(sun.position, a[3], speed*Time.deltaTime);
mars.Rotate(Vector3.up *speed *Time.deltaTime);
jupiter.RotateAround(sun.position, a[4], speed*Time.deltaTime);
jupiter.Rotate(Vector3.up *speed *Time.deltaTime);
saturn.RotateAround(sun.position, a[5], speed*Time.deltaTime);
saturn.Rotate(Vector3.up *speed *Time.deltaTime);
uranus.RotateAround(sun.position, a[6], speed*Time.deltaTime);
uranus.Rotate(Vector3.up *speed *Time.deltaTime);
neptune.RotateAround(sun.position, a[7], speed*Time.deltaTime);
neptune.Rotate(Vector3.up *speed *Time.deltaTime);
moon.RotateAround(earth.position, Vector3.right, 400 *Time.deltaTime);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  3d游戏开发 unity