Generate meteorites in background

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);
    }

}
3 Likes

If you can record a short video clip of this in action @Mattshu I think it would complement your post wonderfully. You can embed video content directly into your post :slight_smile:

1 Like

I did something similar for my laser defender game. This can also be done with a particle system by giving the particle system a sprite sheet of different meteorites.

3 Likes

hello all this is my asteroid storm
yellow circles are “targets” used for calculation of asteroid direction
blue circles are asteroid spawners (they all spawn randomly selected asteroids every 30seconds

Spawner code

using UnityEngine;

public class AsteroidSpawner : MonoBehaviour {

	public GameObject[] asteroids;
	public GameObject[] targets;
    public float startTime;
	private Rigidbody2D rb;
		
	void OnDrawGizmos()
    {
		Gizmos.color = Color.blue;
		Gizmos.DrawWireSphere(transform.position, 0.5f);
	}
	// Use this for initialization
	void Start ()
    {
		InvokeRepeating ("SpawnAsteroid", startTime, 30);
	}

	
	void SpawnAsteroid ()
    {		
		int asteroidType = Random.Range(0, 12);
		switch(asteroidType){
		case 0:
			AsteroidCloned(asteroidType, 50000);
			break;
		case 1:
			AsteroidCloned(asteroidType, 50000);
			break;
		case 2:
			AsteroidCloned(asteroidType, 50000);
			break;
		case 3:
			AsteroidCloned(asteroidType, 50000);
			break;
		case 4:
			AsteroidCloned(asteroidType, 5000);
			break;
		case 5:
			AsteroidCloned(asteroidType, 5000);
			break;
		case 6:
			AsteroidCloned(asteroidType, 5000);
			break;
		case 7:
			AsteroidCloned(asteroidType, 5000);
			break;
		case 8:
			AsteroidCloned(asteroidType, 3000);
			break;
		case 9:
			AsteroidCloned(asteroidType, 3000);
			break;
		case 10:
			AsteroidCloned(asteroidType, 3000);
			break;
		case 11:
			AsteroidCloned(asteroidType, 3000);
			break;
		}
	}
	
	void AsteroidCloned(int version, int impulse)
    {
		GameObject asteroid = (GameObject) Instantiate(asteroids[version], this.transform.position, Quaternion.identity);
		int targetSelect = Random.Range (0, 9);
		Vector2 direction = targets[targetSelect].transform.position - asteroid.transform.position;
		rb = asteroid.GetComponent<Rigidbody2D>();
		rb.AddForce(direction * impulse);
	}
}

SpawnAsterroid() is responsible for selecting type of asteroid and AsteroidCloned() instantiating chosen version with added force impulse to make it move

Asteroid code

using UnityEngine;

public class Asteroid : MonoBehaviour {
    public float hitPoints = 16;
    public GameObject[] meteor;
    public float explosionRange;
    public float particleSize;
    public ParticleSystem explosion;
    public AudioClip explosionSound;
    float hitByProjectile;

    void OnTriggerEnter2D(Collider2D trigger)
    {
        if (trigger.transform.tag == "Shreder")
        {
            Destroy(gameObject);
        }
        else
        {
            hitByProjectile = trigger.GetComponent<Projectile>().damage;
            hitPoints -= hitByProjectile;
            if (hitPoints <= 0)
            {
                Die();
            }
        }
    }

    void Die()
    {
        for (int i = 0; i < 3; i++)
        {
            
        if (meteor[0] != null)
            {
                GameObject newAsteroid = (GameObject)Instantiate(meteor[Random.Range(0, 4)], this.transform.position, Quaternion.identity);
                Rigidbody2D rb = newAsteroid.GetComponent<Rigidbody2D>();
                rb.velocity = new Vector2(Random.Range(-3, 3), Random.Range(-3, 3));
            }
        }
        Destroy(gameObject.GetComponent<Collider2D>());
        Destroy(gameObject.GetComponent<SpriteRenderer>());
        ParticleSystem newExplosion = (ParticleSystem)Instantiate(explosion, this.transform.position, Quaternion.identity);
        ParticleSystem.ShapeModule shape = newExplosion.GetComponent<ParticleSystem>().shape;
        shape.radius = explosionRange;
        ParticleSystem.MainModule size = newExplosion.GetComponent<ParticleSystem>().main;
        size.startSize = particleSize;
        AudioSource.PlayClipAtPoint(explosionSound, transform.position);
        Destroy(gameObject, 0.5f);
        Destroy(newExplosion.gameObject, 0.5f);
    }
}

Die() is responsible for to much things, i’ll remake it sometime.
It’s spawning new asteroids after the original one destroyed
and playing simple particle system as explosion with added sound, I’m using oe PS for all sizes, this is why im exposing so much of PS properties

you can watch it here https://sczot.itch.io/project-deep-space

4 Likes

Hello restlessdan!

Could you explain how you added a sprite sheet to the particle system?

Thanks in advance!!!

2 Likes

sure thing @DebaJr , create a new material from and give it your sprite sheet using the shader: particles/alpha blended then when you have your particle system in place in your scene with it selected go to the inspector and take a look towards the bottom where you see texture sheet animation set up how many sprites are in your sprite sheet, then in renderer add your material that you made.

let me know if you get stuck and I will post a full tutorial on this in its own post, as I don’t want to take over someone else post.

6 Likes

Thank you! It worked perfectly! I was using an incorrect type of shader and getting a weird colored background on the sprite instead of the transparent bg!

Now everything appears to be OK!

Thanks again!
Good bye!

1 Like

Privacy & Terms