Unity2D Circle Chain prototype step 2: adding explosions

Read all posts about "" game

Here we go with the second step of the Unity2D Circle Chain prototype. In the first step we saw how to:

* Create your 2D project
* Set up a custom resolution
* Import your graphic assets
* Create prefabs and add them to the game at runtime
* Create C# scripts and assign them to prefabs, together with graphic assets
* Update sprites position

Now, we are working on the game adding explosions, learning these new concepts

* Detect mouse click
* Get mouse coordinates
* Add tag to prefabs
* Select prefabs with a given tag
* Initializing prefabs with custom variables by communicating with them
* Destroy prefabs

In the same way you created the green circle prefab in first step, create a prefab called redbullet with the image of the red bullet and a C# script called redBulletBehavior.

To add four bullets when the player clicks the mouse, change placingCircles.cs – the Main Camera script – this way:

using UnityEngine;
using System.Collections;

public class placingCircles : MonoBehaviour {

	public GameObject circleInstance = null;
	public GameObject redBulletInstance = null;
	public int greenCircles = 10;

	// Use this for initialization
	void Start () {
		for(int i = 0; i < greenCircles; i ++){
			GameObject greenCircle = Instantiate(circleInstance) as GameObject;
			greenCircle.transform.position = new Vector3(Random.Range(-2.3F, 2.3F),Random.Range(-2.3F, 2.3F), 0);
		}
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetButtonDown("Fire1")) {
			float posX = Input.mousePosition.x-250;
			float posY = Input.mousePosition.y-250;
			for(int i = 0; i<4; i ++){
				GameObject redBullet = Instantiate(redBulletInstance) as GameObject;
				redBullet.transform.position = new Vector3(posX/100, posY/100, 0);
				redBullet.SendMessage("Initialize", i*Mathf.PI/2);
			}
		}
	}
}

I highlighted the new lines, let’s see what they do:

Line 7: adds another global variable to instance the red bullet prefab, as already made with the green circle

Line 20: this is how we detect if the player pressed mouse button

Lines 21-22: get mouse coordinates, remember (0,0) is in the middle of the stage while mouse coordinates have the origin at the bottom left of the stage

Line 23: preparing the loop to create four bullets

Line 24: creation of the bullet itself

Line 25: placing the bullet where the player pressed the mouse

Line 26: sending a message. This will mean we are going to call Initialize function inside red bullet script (redBulletBehavior.cs) passing i*Mathf.PI/2 as argument.

Now that you have a new globar variable, don’t forget to drag red bullet prefab into the new placeholder of the script in Main Camera inspector. Everything is explained in first step.

Now, redBulletBehavior.cs is similar to circleBehavior.cs:

using UnityEngine;
using System.Collections;

public class redBulletBehavior : MonoBehaviour {
	
	public float speed = 5;
	public GameObject greenBulletInstance = null;
	private float xSpeed;
	private float ySpeed;
	
	// Use this for initialization
	void Start () {
		
	}
	
	void Initialize(float angle){
		xSpeed = speed * Mathf.Cos(angle) / 100;
		ySpeed = speed * Mathf.Sin(angle) / 100;
	}
	
	// Update is called once per frame
	void Update () {
		transform.Translate(xSpeed, ySpeed, 0);
		if(transform.position.x < -2.4){
			Destroy(gameObject);
		}
		if(transform.position.x > 2.4){
			Destroy(gameObject);
		}
		if(transform.position.y < -2.4){
			Destroy(gameObject);
		}
		if(transform.position.y > 2.4){
			Destroy(gameObject);
		}
		GameObject[] greenCirclesArray = GameObject.FindGameObjectsWithTag("GreenCircle");
		foreach (GameObject myCircle in greenCirclesArray){
			float distX = (myCircle.transform.position.x - transform.position.x)*100;
			float distY = (myCircle.transform.position.y - transform.position.y)*100;
			if(distX*distX+distY*distY<169){
				for(int i = 0; i<4; i ++){
					GameObject greenBullet = Instantiate(greenBulletInstance) as GameObject;
					greenBullet.transform.position = new Vector3(transform.position.x, transform.position.y, 0);
					greenBullet.SendMessage("Initialize", i*Mathf.PI/2);
				}
				Destroy(gameObject);
				Destroy(myCircle);
			}
		}
	}
}

I would point you on these lines:

Line 16: here is the function called with SendMessage method in placingCircle.cs.

Lines 25, 28, 31, 34: this is how you can destroy the current object

Line 36: having to select all green circles to test for collision with red bullets, I added a “GreenCircle” tag to green circles, then selected them all with FindGameObjectsWithTag method. How can you add a tag to a prefab?

Really easy, in the Inspector choose Tag -> Add Tag then create a tag name – GreenCircle in this case – then again Tag -> GreenCircle.

The rest of the script is really similar to the creation of red bullets, it’s just that now we are creating green bullets, whose script greenBulletBehavior.cs is basically the same as redBulletBehavior.cs.

using UnityEngine;
using System.Collections;

public class greenBulletBehavior : MonoBehaviour {

	public float speed = 5;
	public GameObject greenBulletInstance = null;
	private float xSpeed;
	private float ySpeed;

	// Use this for initialization
	void Start () {
	
	}

	void Initialize(float angle){
		xSpeed = speed * Mathf.Cos(angle) / 100;
		ySpeed = speed * Mathf.Sin(angle) / 100;
	}
	
	// Update is called once per frame
	void Update () {
		transform.Translate(xSpeed, ySpeed, 0);
		if(transform.position.x < -2.4){
			Destroy(gameObject);
		}
		if(transform.position.x > 2.4){
			Destroy(gameObject);
		}
		if(transform.position.y < -2.4){
			Destroy(gameObject);
		}
		if(transform.position.y > 2.4){
			Destroy(gameObject);
		}
		GameObject[] greenCirclesArray = GameObject.FindGameObjectsWithTag("GreenCircle");
		foreach (GameObject myCircle in greenCirclesArray){
			float distX = (myCircle.transform.position.x - transform.position.x)*100;
			float distY = (myCircle.transform.position.y - transform.position.y)*100;
			if(distX*distX+distY*distY<169){
				for(int i = 0; i<4; i ++){
					GameObject greenBullet = Instantiate(greenBulletInstance) as GameObject;
					greenBullet.transform.position = new Vector3(transform.position.x, transform.position.y, 0);
					greenBullet.SendMessage("Initialize", i*Mathf.PI/2);
				}
				Destroy(gameObject);
				Destroy(myCircle);
			}
		}
	}
}

And this is the result:

Click on the stage to fire red bullets and hopefully start a chain reaction.

Next time, we’ll add some particle effect to give this old game a twist, meanwhile download the entire project.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers