-
-
Save unitycoder/954e2edf5fcdc412b70a3a9b5f99c1ac to your computer and use it in GitHub Desktop.
Script for StarField background in Unity from this tutorial: https://www.youtube.com/watch?v=yu23OAd_Wrw&list=LL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using Random = UnityEngine.Random; | |
public class StarField : MonoBehaviour | |
{ | |
private Transform thisTransform; | |
private ParticleSystem.Particle[] points; | |
public int starsMax = 100; | |
public float starSize = 1f; | |
public float starDistance = 10f; | |
public float starClipDistance = 1f; | |
// do not touch, internal math stuff | |
private float starDistanceSqr; | |
private float starClipDistanceSqr; | |
private ParticleSystem ps; | |
// Use this for initialization | |
private void Start() | |
{ | |
thisTransform = transform; // caching the transform | |
starClipDistanceSqr = starClipDistance * starClipDistance; | |
starDistanceSqr = starDistance * starDistance; | |
ps = GetComponent<ParticleSystem>(); | |
var main = ps.main; | |
main.simulationSpace = ParticleSystemSimulationSpace.World; | |
} | |
private void CreateStars() | |
{ | |
points = new ParticleSystem.Particle[starsMax]; | |
for (int i = 0; i < starsMax; i++) | |
{ | |
points[i].position = Random.insideUnitSphere.normalized * starDistance + thisTransform.position; | |
points[i].color = new Color(1, 1, 1, 1); | |
points[i].size = starSize; | |
} | |
} | |
// Update is called once per frame | |
private void Update() | |
{ | |
if (points == null) | |
{ | |
CreateStars(); | |
} | |
for (int i = 0; i < starsMax; i++) | |
{ | |
if ((points[i].position - thisTransform.position).sqrMagnitude > starDistanceSqr) | |
{ | |
points[i].position = Random.insideUnitSphere.normalized * starDistance + thisTransform.position; | |
} | |
if ((points[i].position - thisTransform.position).sqrMagnitude <= starDistanceSqr) | |
{ | |
float percent = (points[i].position - thisTransform.position).sqrMagnitude / starClipDistanceSqr; | |
points[i].color = new Color(1, 1, 1, percent); | |
points[i].size = percent * starSize; | |
} | |
} | |
ps.SetParticles(points, points.Length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment