GameDev Tutorial – Basic Circle Chain Engine Using Unity3D – parts 2 and 3

Read all posts about "" game

I hope you enjoyed the 1st part of the Circle Chain Engine using Unity3D. Alex Cançado published the 2nd and 3rd step and I am going to group these two steps of his fantastic tutorial in this post:

Time to put some mouse interaction.

1. add the new textures: red circle, bullet red; configure texture type to advanced, uncheck generate mipmap and filter mode to point.

2. drag and drop the greencircleprefab from prefab folder to the hierarchy. drag and drop the red circle texture to this and rename to RedCircle. Remove the GreenCricle script from it. We will create a script to this object later.

3. But we still need create our Bullet prefab.

To make it simple, just duplicate the RedCircle object from hierarchy panel with Command+D or (Control+D in windows?). Then rename this new object to RedBulletPrefab.

Drag n drop the bullet texture to it. We will add a Bullet script later. All done, drag n drop the RedBulletPrefab from Hierarchy to your Prefab folder in your project files, so we create a Prefab of the bullet object.

Since we will instantiate bullet objects by code, you can delete the RedBulletPrefab from the Hierarchy panel.

4. Now lets add some player control to RedCircle: go to your script folder and create a new c# script RedCircle; Don’t forget to add this script to the RedCircle.

using UnityEngine;
using System.Collections;
public class RedCircle : MonoBehaviour {
     // for mouse controller
     public float mousePos;
     // for 2d position calc
     public Camera cam;
     // prefab to be instantieated
     public GameObject redBulletPrefab;
     public float redBulletXSpeed;
     public float redBulletYSpeed;
     public float bulletSpeed = 5;
     // Use this for initialization
     void Start () {
          cam = Camera.main.GetComponent<Camera>(); // get the Main Camera instance
     }
     // Update is called once per frame
     void Update () {
          attachObjectToMouse ();
          // if left mouse clicks instantiate our bullets
          if (Input.GetMouseButtonDown(0)){
               // 4 directions 
               for (int i = 0; i < 4; i++) {
                    // calc the direction of the bullet
                    redBulletXSpeed = bulletSpeed * Mathf.Cos(i * Mathf.PI / 2); //redBullet.xSpeed=bulletSpeed*Math.cos(i*Math.PI/2);
                    redBulletYSpeed = bulletSpeed * Mathf.Sin(i * Mathf.PI / 2); //redBullet.ySpeed=bulletSpeed*Math.sin(i*Math.PI/2);
                    // create a instance of bullet
                    GameObject clone = Instantiate(redBulletPrefab, transform.position, transform.rotation) as GameObject;
                    clone.SendMessage("setBulletXSpeed", redBulletXSpeed);
                    clone.SendMessage("setBulletYSpeed", redBulletYSpeed);
               }
          }
     }
     private void attachObjectToMouse () {
          Vector3 screenPos = Input.mousePosition; 
          // need convert 2d position (from mouse) to 3d world position
          Vector3 worldPos = new Vector3(cam.ScreenToWorldPoint(screenPos).x, cam.ScreenToWorldPoint(screenPos).y, cam.ScreenToWorldPoint(screenPos).z); 
          // set the red circle object position
          gameObject.transform.position = worldPos;
     }
}

5. Now you can movement the Red Circle with mouse! But we still need create a script to control the bullets and then add this script to our RedBulletPrefab prefab:

using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
     // objects pooling: http://channel9.msdn.com/Events/Windows-Camp/Building-Windows-Games-with-Unity/Deep-dive-Tips-tricks-for-porting-games-from-other-platforms-to-Windows-8
     // bullet 
     public float redBulletXSpeed;
     public float redBulletYSpeed;
     // for 2d position calc
     public Camera cam;
     public float screenX; // = Camera.current.ScreenToWorldPoint( new Vector3 (Screen.width, 0, 0)).x;
     public float screenY; // = Camera.current.ScreenToWorldPoint( new Vector3 (0, Screen.height, 0)).y;
     // Use this for initialization
     void Start () {
          cam = Camera.main.GetComponent<Camera>(); // get the Main Camera instance
     }
     // Update is called once per frame
     void Update () {
          transform.Translate( new Vector3(redBulletXSpeed, redBulletYSpeed, 0 ) * Time.deltaTime);
          //transform.Translate( new Vector3(0f, ySpeed*Time.deltaTime, 0f) );
          // get screen limits
          getCurrentMaxWorldScreen();
          // destroy bullets if off screen
          deleteOffScreenObject();
     }
     // get our screen limits
     public void getCurrentMaxWorldScreen(){
          screenX = cam.ScreenToWorldPoint( newVector3 (Screen.width, 0, 0)).x;//Camera.current.ScreenToWorldPoint( new Vector3 (Screen.width, 0, 0)).x;
          screenY = cam.ScreenToWorldPoint( new Vector3 (0, Screen.height, 0)).y;
     }
     public void deleteOffScreenObject(){
          // if the GreenCircle goes out the screen we manage to put it back
          if(transform.position.x > (screenX)){
               Destroy(this.gameObject);
          }
          if(transform.position.x < -screenX){
               Destroy(this.gameObject);
          }
          if(transform.position.y > screenY){
               Destroy(this.gameObject);
          }
          if(transform.position.y < -screenY){
               Destroy(this.gameObject);
          }
     }
     public void setBulletXSpeed(float speedX){
          redBulletXSpeed = speedX;
     }
     public void setBulletYSpeed(float speedY){
     redBulletYSpeed = speedY;
     }
}

6. Now it’s possible “shot” when we press the left mouse button:

You can download the project here. Open the scene in Assets > CircleChain02 > Scenes and try it!

What we need to do in this third part:

. RedBullet collides with GreenCircle.

. GreenCircle spawn GreenBullets.

. repeat the process each collision between “bullets” objects and GreenCircles.

Basically we need add physics components to GameObjects, then add colliders.

1. In the prefab folder, select RedBulletPrefab. In the Inspector panel, at bottom, click the button Add Component > Physics > Rigidbody. Then uncheck “use gravity”, check “Is kinematic” and I checked too the z position and x, y, z rotation freeze options.

2. With RedBulletPrefab selected, add a new physics component, collider. For bullets I choose Box Collider, for the Green Circle I added an Sphere Collider. Just check “Is trigger” since we will use C# script to control collisions.

3. Do the steps 1 and 2 above to GreenCirclePrefab.

4. Let’s create a new prefab, GreenBulletPrefab. It’s based in the RedBulletPrefab, so drag and drop RedBulletPrefab into Hierarchy panel. Rename to GreenBulletPrefab. Go to Texture folder and assuming that you have already imported the greenbullet.png (Texture type: advanced, uncheck generate mip maps, filter mode: point), drag and drop into the new GreenBulletPrefab. Then drag and drop GreenBulletPrefab to the Prefab objects. Now you can delete GreenBulletPrefab from Hierarchy panel, since we will instantiate this object with C# script.

5. Open the CircleChain script in the Script folder. Here we need check for collisions and spawn the green bullets, then destroy the green circle object. Basically we will add this:

// prefab to be instantieated
public GameObject greenBulletPrefab;
public float greenBulletXSpeed;
public float greenBulletYSpeed;
public float bulletSpeed = 3;
…
// check for collisions
void OnTriggerEnter(Collider obj) {
     // for debug
     //print(obj.gameObject.name);
     // if this object collides with the red/green Bullet
     if (obj.gameObject.name == "RedBulletPrefab(Clone)" || obj.gameObject.name == "GreenBulletPrefab(Clone)") {
          // calc the new bullets positions
          for (int i = 0; i < 4; i++) {
               // calc the direction of the bullet
               greenBulletXSpeed = bulletSpeed * Mathf.Cos(i * Mathf.PI / 2); //redBullet.xSpeed=bulletSpeed*Math.cos(i*Math.PI/2);
               greenBulletYSpeed = bulletSpeed * Mathf.Sin(i * Mathf.PI / 2); //redBullet.ySpeed=bulletSpeed*Math.sin(i*Math.PI/2);
               // create a instance of bullet (green)
               GameObject clone = Instantiate(greenBulletPrefab, transform.position, transform.rotation) as GameObject;
               clone.SendMessage("setBulletXSpeed", greenBulletXSpeed);
               clone.SendMessage("setBulletYSpeed", greenBulletYSpeed);
          }
          // after all, destroy the green circle
          Destroy(this.gameObject);
     }
}

We used this for our RedCircle script.

Thats it!

Done!

Download here the new complete project files: Unity Circle Chain Part 3.

Just open the “scene03” in the scene folder.

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

215 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
// Stairs
// 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