Create a game like Spring Ninja with Unity – step 2

Read all posts about "" game

Here we go with the second step of the Spring Ninja prototype made with Unity.

This is what we are going to get at the end of the post:

You know how play: press and hold the mouse to charge, release to jump. The game is an endless runner so you will always find plenty of poles where to jump on.

You don’t need to add or edit any prefab to the project you created in the first step, but to improve gameplay is highly recommended you check “Fixed Angle” in the Rigidbody 2D inspector to keep your “ninja” in a fixed angle and prevent it to fall down too often.

Then here are the four scripts, with new/modified lines highlighted: MainScript:

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
	private bool isCharging = false; // is the ninja charging the jump?
	private float minPoleGap = 1.5f; // min distance between two poles
	private float maxPoleGap = 2.5f; // max distance between two poles 

	// function executed when the script is launched
	void Start () {
		// placing the ninja prefab on the stage
		Instantiate(ninjaObject);
		// placing the pole prefabs on the stage
		placePole (-2.5f);
	}

	void placePole(float posX){
		// if the pole is not too far, then place it
		if(posX<10f){
			// adding the prefab to the stage
			Instantiate(poleObject);
			// position the pole prefab
			poleObject.transform.position = new Vector2(posX,-1.5f-Random.value*2.5f);
			// determining next pole position
			posX += minPoleGap+Random.value*(maxPoleGap-minPoleGap);
			// try to place another pole
			placePole (posX);
		}
	}

	// function executed at each frame
	void Update () {
		// mouse button down and ninja is not charging and not jumping/falling - that is its y velocity is zero?
		if (Input.GetButtonDown("Fire1") && GameObject.FindWithTag("Player").GetComponent<Rigidbody2D>().velocity.y==0 && !isCharging) {
			// let's place the power bar on the stage
			GameObject powerBar = Instantiate(powerBarObject) as GameObject;
			// now the player is charging
			isCharging = true;
			// once the player is charging, check if there's enough poles
			GameObject[] poles = GameObject.FindGameObjectsWithTag("Pole");
			float maxPoleDistance = 0;
			foreach (GameObject pole in poles){
				// looking for the rightmost pole
				maxPoleDistance = Mathf.Max(maxPoleDistance,pole.transform.position.x);
			}
			// if the rightmost pole is not too far, try to place another pole.
			if(maxPoleDistance<10f){
				placePole (maxPoleDistance+minPoleGap+Random.value*(maxPoleGap-minPoleGap));
			}
		}
		// mouse button released and the ninja is charging but not jumping/falling - that is its y velocity is zero?
		if (Input.GetButtonUp("Fire1") && GameObject.FindWithTag("Player").GetComponent<Rigidbody2D>().velocity.y==0 && isCharging) {
			// player is no longer charging
			isCharging = false;
			// get the game object tagged as "Power"
			GameObject powerObject = GameObject.FindWithTag("Power");
			// inside the object tagged as "Power", get PowerScript script
			PowerScript script = powerObject.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+50);
		}
	}

}

PoleScript:

using UnityEngine;
using System.Collections;

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

	void Update(){
		// getting the real position, in pixels, of the pole on the stage
		Vector2 stagePos = Camera.main.WorldToScreenPoint(transform.position);
		// if the pole leaves the stage...
		if (stagePos.x < -20){
			Destroy(gameObject);
		}
	}

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

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

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);
		}
		transform.position = new Vector2(-2.5f,transform.position.y);
	}

	void Jump(float jumpForce){
		// adding a vertical force to make the ninja jump
		GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce));
		// get all objects tagged with "Pole"
		GameObject[] poles = GameObject.FindGameObjectsWithTag("Pole");
		foreach (GameObject pole in poles){
			// send them all "scroll" message
			pole.SendMessage("scroll");
		}
	}

	void OnCollisionEnter2D(){
		// get all objects tagged with "Pole"
		GameObject[] poles = GameObject.FindGameObjectsWithTag("Pole");
		foreach (GameObject pole in poles){
			// send them all "scroll" message
			pole.SendMessage("stop");
		}
	}
}

And our Spring Ninja prototype made with Unity is completed. Download the source code of 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