I thought’d it be cool to make use of the meteorite sprites in the assets supplied with this course. So I made a script that randomly throws different meteorites in the background. They’re meant to be background props but if you want extra challenge, enable collision and cause damage to the player.
Build meteorite prefabs by dragging a meteorite sprite onto the scene and giving it a name and Rigidbody 2D component. (Delete the GameObject after creating prefab)
Create an empty GameObject and attach a new script with the contents below. Then in the Inspector, decide how many different meteorites you would like, and set the Size
value accordingly. Then drag meteorite prefabs into the Element
list.
using UnityEngine;
public class MeteorGenerator : MonoBehaviour {
public GameObject[] meteorites;
public float minSpeed = 2f;
public float maxSpeed = 10f;
public float freq = 0.5f;
public float rotateSpeed = 2f;
void Generate()
{
float distance = transform.position.z - Camera.main.transform.position.z;
Vector3 leftMost = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distance));
Vector3 rightMost = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distance));
// Creates a random meteorite (from the meteorite array) at the top of the playing field at a random X position
GameObject meteorite = Instantiate(meteorites[Random.Range(0,meteorites.Length)],
new Vector3(Random.Range(leftMost.x, rightMost.x), 5f, 2f),
Quaternion.identity) as GameObject;
// Give meteorites variable speeds for depth
meteorite.GetComponent<Rigidbody2D>().velocity = new Vector2(0f, -Random.Range(minSpeed, maxSpeed));
meteorite.transform.parent = transform;
}
void Update()
{
// Look familiar?
float probability = Time.deltaTime * freq;
if (Random.value < probability)
Generate();
if (transform.childCount > 0) // If there are meteorites in the playing field,
foreach (Transform child in transform) // then rotate each meteorite.
child.transform.Rotate(Vector3.forward * -rotateSpeed);
}
}