Create a game like Spring Ninja with Unity – step 1

Read all posts about "" game

I received a lot of good feedback both with my Spring Ninja Phaser prototype post and with Flappy Bird Unity prototype, so I decided to merge the best of both concepts and create a Spring Ninja prototype made with Unity.

This will also allow readers to understand the code behind the creation of the Phaser prototype.

The tutorial will be split in two parts, because these are the first Unity tutorials on this blog and probably some readers are still not that used to Unity mechanics.

Let’s jump straight to the point, and let’s see the assets used in the prototype:

What we have in Hierarchy window is the Main Camera and a Game Engine empty object, where we are going to embed the main script. The game is also set to run at 640×480. If you have troubles to set up the camera, create game objects, change resolution or create and expand game prefabs, like the one we are going to see in a moment, there’s a detailed tutorial here.

Now, let’s have a look at Assets window:

* mainScene: the main scene, save it before you close the project

* MainScript: the main script, which will be added to Game Engine

* ninja: the ninja PNG image

* ninjaPrefab: the prefab of the ninja, containing the ninja image, NinjaScript script, Rigidbody 2D component and Box Collider 2D component both with default attributes

* NinjaScript: the script to be attached to ninjaPrefab

* pole: the pole PNG image

* polePrefab: the prefab of the pole, containing the pole image, PoleScript script, Rigidbody 2D component with Is Kinematic checked and Box Collider 2D component with default attributes.

* PoleScript: the script to be attached to polePrefab

* powerbar: the power bar PNG image

* powerbarPrefab: the prefab of the power bar, containing the power bar image and PowerScript script. No physics for this prefab.

* PowerScript: the script to be attached to powerbarPrefab

With this in mind, have a look at what we are going to build:

Press and hold the mouse to charge, select to jump. Unfortunately, you will fall to death, but more poles where to land on will come in next step.

Now, it’s time to have a look at the scripts, starting from MainScript. I am also using Unity’s Tags and Messages. You can find information about these concepts in the post Unity2D Circle Chain prototype step 2: adding explosions.

using UnityEngine;
using System.Collections;

public class MainScript : MonoBehaviour {

	// all these variables will be declared in the inspector

	public GameObject ninjaObject; // the ninja prefab	
	public GameObject poleObject; // the pole prefab
	public GameObject powerBarObject; // the pole bar prefab
	public float jumpForce; // jump force - vertical only
	public float maxJumpForce; // maximum vertical jump force
	public bool ninjaJumping = true; // is the ninja jumping? we start with "true" because the ninja will fall from the top of the stage

	// function executed when the script is launched

	void Start () {
		// placing the ninja prefab on the stage
		Instantiate(ninjaObject);
		// placing the pole prefab on the stage
		Instantiate(poleObject);
		// setting pole position
		poleObject.transform.position = new Vector2(-2.5f, -2f);
	}

	// function executed at each frame

	void Update () {
		// mouse button down and the ninja is not jumping?
		if (Input.GetButtonDown("Fire1") && !ninjaJumping) {
			// let's place the power bar on the stage
			GameObject powerBar = Instantiate(powerBarObject) as GameObject;
		}
		// mouse button released and the ninja is not jumping?
		if (Input.GetButtonUp("Fire1") && !ninjaJumping) {
			// the ninja now is jumping 
			ninjaJumping = true;
			// get the game object tagged as "Power"
			GameObject main = GameObject.FindWithTag("Power");
			// inside the object tagged as "Power", get PowerScript script
			PowerScript script = main.GetComponent("PowerScript") as PowerScript;
			// destoy the power bar
			Destroy(GameObject.FindWithTag("Power"));
			// find the object tagged as "Player" and send "Jump" message, with the proper force
			GameObject.FindWithTag("Player").SendMessage("Jump",maxJumpForce*script.chargePower);
			// get all objects tagged with "Pole"
			GameObject[] poles = GameObject.FindGameObjectsWithTag("Pole");
			foreach (GameObject pole in poles){
				// send them all "scroll" message
				pole.SendMessage("scroll");
			}
		}
	}

}

As you can see, the main script does most of the dirty job, leaving other scripts just minor things. Let’s see PoleScript:

using UnityEngine;
using System.Collections;

public class PoleScript : MonoBehaviour {
	
	void Start () {
		// tagging the object as Pole
		gameObject.tag = "Pole";
	}

	void scroll(){
		// assigning pole an horizontal speed
		GetComponent<Rigidbody2D>().velocity = new Vector2(-2f, 0f);
	}
}

Then PowerScript:

using UnityEngine;
using System.Collections;

public class PowerScript : MonoBehaviour {

	public float chargePower = 0;

	void Start () {
		// tagging the object as "Power"
		tag = "Power";
		// horizontally scaling the object to zero
		transform.localScale = new Vector2(0f,1f);
	}

	void Update () {
		// adding chargePower the elapsed time until it reaches 1
		chargePower = Mathf.Min(chargePower+Time.deltaTime,1f);
		// setting local scale accordingly
		transform.localScale = new Vector2(chargePower,1f);
		// finally updating its position to give the feeling it's growing from left to right
		transform.position = new Vector2(-3.0f+chargePower/2, 2.15f);
	}
}

and finally NinjaScript:

using UnityEngine;
using System.Collections;

public class NinjaScript : MonoBehaviour {

	void Start () {
		// placing the ninja
		transform.position = new Vector2(-2.5f, 2f);
		// tagging it as "Player"
		tag = "Player";
	}

	void Update(){
		// checking if the ninja falls down the stage, in this case restart the game
		Vector2 stagePos = Camera.main.WorldToScreenPoint(transform.position);
		if (stagePos.y < 0){
			Application.LoadLevel(Application.loadedLevel);
		}
	}

	void Jump(float jumpForce){
		// adding a vertical force to make the ninja jump
		GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce));
	}

	void OnCollisionEnter2D(){
		// when the ninja collides, find "Game Engine" object, then find "MainScript" script and set its ninjaJumping variable to false
		GameObject main = GameObject.Find("Game Engine");
		MainScript script = main.GetComponent("MainScript") as MainScript;
		script.ninjaJumping = false;
	}
}

During next step we’ll complete the prototype, meanwhile download the 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

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