Circular endless runner featuring double jump built with Unity and C# using only trigonometry – how to move spikes and add first collision detection

Read all posts about "" game

Here we go with another step of Circular Endless Runner creation, this time using Unity and C#.

In previous step we built the prototype of the circular endless runner featuring double jump without using any physics engine, just good old trogonometry.

This time I am pushing things a little further, adding moving spikes and a basic collision detection.

The collision detection forgives a lot but that’s what today players want: say “heeew it almost got me”.

Have a look at the prototype:

Click to jump or double jump. If you hit a spike, the game restarts.

Actually collision detection does not check for circle/triangle collision, it only checks for the distance between the very top pixel of the spike and the ball.

But it works anyway, the game is fun and you can easily port it in any other language since it does not rely on any specific Unity physics engine.

The code is quite a mess but I am going to improve it next time, and will add comments too.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class mainScript : MonoBehaviour {

	public GameObject player;
	public GameObject spikeObject;
	public float bigCircleRadius;
	public float smallCircleRadius;
	public float revolutionSpeed;
	public float currentAngle;
	private float revolutions;
	public float gravity;
	public float[] jumpForce;
	private float jumpOffset = 0;
	private int jumps = 0;
	private float currentJumpForce = 0;
	private float spikeHeight;

	void Start () {
		revolutions = bigCircleRadius / smallCircleRadius + 1;
		spikeHeight = spikeObject.GetComponent<Renderer> ().bounds.size.x;
		for (int i = 0; i < 6; i++) {
			GameObject spike = Instantiate (spikeObject);
			placeSpike (spike, Mathf.FloorToInt(i / 2) + 1);
		}
	}

	void Update () {
		handleJumps ();
		handleRevolution (Time.deltaTime);
		handleSpikes ();
	}
		
	void placeSpike(GameObject spike, int quadrant){
		float totalRadius = bigCircleRadius + spikeHeight / 2 - 0.01f;
		int randomAngle = Random.Range (quadrant * 90, (quadrant + 1) * 90);
		spike.transform.eulerAngles = new Vector3(0, 0, randomAngle);
		float radians = randomAngle * Mathf.Deg2Rad;
		spike.transform.position = new Vector2 (totalRadius * Mathf.Cos (radians), totalRadius * Mathf.Sin (radians));
		spike.GetComponent<spikeScript>().isApproaching = false;
		spike.GetComponent<spikeScript>().quadrant = quadrant;
	}

	void handleJumps(){
		if (Input.GetButtonDown ("Fire1")) {
			if (jumps < 2) {
				jumps++;
				currentJumpForce = jumpForce [jumps - 1];
			}	
		}
		if (jumps > 0) {
			jumpOffset += currentJumpForce;
			currentJumpForce -= gravity;
			if (jumpOffset < 0) {
				jumpOffset = 0;
				jumps = 0;
				currentJumpForce = 0;
			}
		}
	}

	void handleRevolution(float elapsedTime){
		currentAngle += 360f * elapsedTime / revolutionSpeed;
		currentAngle = (currentAngle + 360) % 360;
		Vector2 newPosition = player.transform.position;
		float radians = currentAngle * Mathf.Deg2Rad;
		float totalRadius = bigCircleRadius + smallCircleRadius + jumpOffset;
		newPosition.x = totalRadius * Mathf.Cos (radians);
		newPosition.y = totalRadius * Mathf.Sin (radians);
		player.transform.position = newPosition;
		player.transform.Rotate (0, 0, 360f * revolutions * elapsedTime / revolutionSpeed);
	}

	void handleSpikes(){
		GameObject[] spikes = GameObject.FindGameObjectsWithTag ("Spike");
		foreach (GameObject spike in spikes) {
			float spikeAngle = spike.transform.localRotation.eulerAngles.z;
			float angleDifference = Mathf.Abs(Mathf.DeltaAngle (spikeAngle, currentAngle));
			if (angleDifference < 10 &amp;&amp; !spike.GetComponent<spikeScript> ().isApproaching) {
				spike.GetComponent<spikeScript> ().isApproaching = true;
			}
			if (angleDifference > 20 &amp;&amp; spike.GetComponent<spikeScript> ().isApproaching) {
				placeSpike (spike, (spike.GetComponent<spikeScript> ().quadrant - 3) % 4);
			}
			if (spike.GetComponent<spikeScript> ().isApproaching) {
				checkSpikeCollision (spikeAngle);
			}
		}
	}

	void checkSpikeCollision(float spikeAngle){
		float totalSpikeHeight = bigCircleRadius + spikeHeight / 2;
		float radians = spikeAngle * Mathf.Deg2Rad;
		Vector2 spikeTop = new Vector2 (totalSpikeHeight * Mathf.Cos (radians), totalSpikeHeight * Mathf.Sin (radians));
		float minimumDistance = smallCircleRadius;
		float distance = Vector2.Distance (spikeTop, player.transform.position);
		if (distance < minimumDistance) {
			SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
		}
	}
}

Next time I’ll add some collectibe item, meanwhile download the complete 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