“Back to Square One” prototype made with Unity and LeanTween

Read all posts about "" game
If you liked the HTML5 prototype of “Back to Square One” I showed you last week, you will be happy to know I ported the code to Unity using C# and LeanTween. What is LeanTween? Well, you should know Unity is awesome but it does not natively support tweens like Phaser does. Too good there are some interesting tween libraries in the asset store, most of them free, and after a quick overview I choosed LeanTween. Apart from that, I tried to keep the code as similar to its Phaser counterpart as possible, I am just using another sprite as pivot point to rotate the square as with Unity you can’t change the registration point of a sprite at runtime. Actually, you can try some workaround but it’s a hassle. Guaranteed. It’s much easier to create a sprite as pivot point and attach the square to be rotated as child. Have a look at what we are going to create:
Click on the stage to make the square roll and the terrain scroll. You will see two little red square. The one you see at the bottom right of the square is the pivot point, while the one you see as you start moving the square is the parent of all terrain tiles. I am assuming you know how to create prefab, scripts and cameras in Unity, if you are in trouble check my Unity Flappy Bird prototype which explains all the basic concepts. I placed all the code in one single class, so have a look at the code commented line by line:
using UnityEngine; using System.Collections; public class MainScript : MonoBehaviour { // public variables. Values are set in the editor // the square object public GameObject squareObject; // the pivot object public GameObject pivotObject; // tansition speed, in seconds public float transitionSpeed; // private variables. Values are set in the script // the hero!! private GameObject squareHero; // hero pivot point. Basically another GameObject, the parent of squareHero private GameObject squareHeroPivot; // terrain pivot Point, the parent of all terrain tiles private GameObject terrainPivot; // can the hero rotate? private bool canRotate = true; // array of two elements which will contain ground colors private Color[] colors = new Color[2]; // this function is executed when the script is initialized. void Start () { // filling “colors” array colors [0] = Color.blue; colors [1] = Color.green; // placing squareHero on the centre of the stage squareHero = Instantiate(squareObject); // placing squareHeroPivot on the centre of the stage squareHeroPivot = Instantiate(pivotObject); // placing the pivot point in the lower right corner of squareHero squareHeroPivot.transform.position = new Vector2 (0.2f, -0.2f); // making squareHero child of squareHeroPivot squareHero.transform.parent = squareHeroPivot.transform; // now it’s time to place the terrain pivot point terrainPivot = Instantiate(pivotObject); // we are going to add 10 terrain tiles, enough for our 320 pixels wide game for (int i = 0; i < 10; i++) { // placing a terrain tile on the centre of the stage GameObject squareTerrain = Instantiate (squareObject); // placing it accordingly squareTerrain.transform.position = new Vector2 (-1.6f + i * 0.4f, -0.4f); // giving the tile a tint color squareTerrain.GetComponent ().material.color = colors[i % 2]; // making the tile child of the terrain pivot squareTerrain.transform.parent = terrainPivot.transform; } } // this function is executed at each frame. void Update () { // this is how we check if the player clicked if (Input.GetButtonDown (“Fire1”) && canRotate) { // setting canRotate to false to prevent the player to rotate the square while it’s already rotating canRotate = false; // getting current squareHeroPivot rotation, in degrees float currentRotation = squareHeroPivot.transform.rotation.eulerAngles.z; // getting current hero x position float currentHeroPosition = squareHeroPivot.transform.position.x; // getting current terrain x position float currentTerrainPosition = terrainPivot.transform.position.x; // the core of the script: LeanTween in action // rotateZ tweens rotation around Z axis, to currentRotation – 90 at “transitionSpeed” speed. // once completed, tweenComplete function is executed. LeanTween.rotateZ(squareHeroPivot, currentRotation – 90f, transitionSpeed).setOnComplete(tweenComplete); // moveX tweens position along x axis, to currentHeroPosition – 0.4 at “transitionSpeed” speed. LeanTween.moveX (squareHeroPivot, currentHeroPosition – 0.4f, transitionSpeed); LeanTween.moveX (terrainPivot, currentTerrainPosition – 0.4f, transitionSpeed); } } // tweenComplete function is called when the Z rotation has been completed void tweenComplete(){ // the player can rotate again canRotate = true; // getting square pivot rotation, in degrees int rotation = (int)squareHeroPivot.transform.eulerAngles.z; // reposition the pivot so that it’s always in the lower right corner of the square squareHeroPivot.transform.position = new Vector2 (0.2f, -0.2f); // changing hero position according to its pivot rotation, ready to start next rotation // this part can and should be optimized switch (rotation) { case 270: squareHero.transform.localPosition = new Vector2 (-0.2f, -0.2f); break; case 180: squareHero.transform.localPosition = new Vector2 (0.2f, -0.2f); break; case 90: squareHero.transform.localPosition = new Vector2 (0.2f, 0.2f); break; case 0: squareHero.transform.localPosition = new Vector2 (-0.2f, 0.2f); break; } // by default we assume the leftmost child of the tarrain is the first children… Transform leftmostChild = terrainPivot.transform.GetChild (0).transform; // … but we loop through all other children comparing their x position to find the actual leftmost child for (int i = 1; i < 10; i++) { if (terrainPivot.transform.GetChild (i).transform.position.x < leftmostChild.transform.position.x) { leftmostChild = terrainPivot.transform.GetChild (i).transform; } } // at this time we move the leftmost child after the rightmost tile, creating an infinite terrain without deleting old tiles and creating new tiles leftmostChild.transform.position = new Vector2 (2f, -0.4f); } }
That’s all at the moment, I plan to turn both this prototype and the Phaser prototype into two simple games, and at the moment you can 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

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