How to create infinite starfield for space scene in Unity
Published: Dec. 11, 2013, 8:31 p.m. #starfield #unity #GameDev
Hello guys!
In this tutorial I'll explain how to create starfield in Unity 3D engine. This principle explained here is apliable to any other game engine. However, we will use Shuriken particle system which is available in Unity 3.5+.
The main principle we implement here is constantly spawning the controlled number of particles around the player's position.
I won't be explaining how to create/paint the skybox nor how to create flythrough camera. These topics are covered in these tutorials:
- Creating nebula skybox
- Creating flythrough camera
The final script will look like this:
using UnityEngine;
using System.Collections;
public class InfinteStarfield : MonoBehaviour {
private Transform tx;
private ParticleSystem.Particle[] points;
public int starsMax = 100;
public float starSize = 1;
public float starDistance = 10;
public float starClipDistance = 1;
private float starDistanceSqr;
private float starClipDistanceSqr;
// Use this for initialization
void Start () {
tx = transform;
starDistanceSqr = starDistance * starDistance;
starClipDistanceSqr = starClipDistance * starClipDistance;
}
private void CreateStars() {
points = new ParticleSystem.Particle[starsMax];
for (int i = 0; i < starsMax; i++) {
points[i].position = Random.insideUnitSphere * starDistance + tx.position;
points[i].color = new Color(1,1,1, 1);
points[i].size = starSize;
}
}
// Update is called once per frame
void Update () {
if ( points == null ) CreateStars();
for (int i = 0; i < starsMax; i++) {
if ((points[i].position - tx.position).sqrMagnitude > starDistanceSqr) {
points[i].position = Random.insideUnitSphere.normalized * starDistance + tx.position;
}
if ((points[i].position - tx.position).sqrMagnitude <= starClipDistanceSqr) {
float percent = (points[i].position - tx.position).sqrMagnitude / starClipDistanceSqr;
points[i].color = new Color(1,1,1, percent);
points[i].size = percent * starSize;
}
}
// older versions of Unity
// particleSystem.SetParticles ( points, points.Length );
// Unity 5.4+ and probably some sooner versions
GetComponent().SetParticles(points, points.Length);
}
}
EDIT:
There was a small change in Unity u cant access 'particleSystem' directly but as @Kore wrote some time ago: +Mee Works in 5.4beta but you need to switch line 64.
from:
particleSystem.SetParticles(points, points.Length);
to:
GetComponent<ParticleSystem>().SetParticles(points, points.Length);
Hope you will learn something here and there and if you have any questions just post them below the video.
Thanks for watching!