Unity hook like the one seen on iOS Mikey Hooks game

Read all posts about "" game
As you can imagine, I liked a lot Mikey Hooks’ hook function, and I showed you working prototypes made with AS3+Box2D, AS3+Nape and Phaser+Box2D. Now it’s time to see the same thing working with Unity. During the creation of this prototype you will learn, among other things, how to: * create distance joints on the fly * select a rigid body with the mouse * draw lines on the stage First, let’s have a look at the prefabs 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 * ground: the ground PNG image * player: the player PNG image * wall: the wall PNG image * ground prefab: the prefab of the ground, containing the ground image, Rigidbody 2D component with Is Kinematic checked and Box Collider 2D component with default attributes * wall prefab: the prefab of the wall, containing the wall image, Rigidbody 2D component with Is Kinematic checked and Box Collider 2D component with default attributes. Alto it’s tagged as “Wall”. Refer to this post if you aren’t familiar with Unity Tag feature. * player prefab: the prefab of the player, containing the player image, Rigidbody 2D component and Box Collider 2D component with default attributes. With this in mind, have a look at what we are going to build – remember it probably won’t work on Chrome:
You should know how to play: click and hold on a wall to fire the hook, release to destroy the hook. And this is the commented source code of MainScript:
using UnityEngine; using System.Collections; public class MainScript : MonoBehaviour { // the floor/ground prefab public GameObject floorObject; // the wall prefab. Player will be able to fire the hook on walls public GameObject wallObject; // the player prefab public GameObject playerObject; // thePlayer variable will be playerObject instance during the game private GameObject thePlayer; // the distance joint we are going to build on the fly during the game private DistanceJoint2D hookJoint; // there is no debug draw mode to show distance joints so I am going to use a LineRenderer to draw it manually private LineRenderer rope; // Use this for initialization void Start () { // initializing rope’s LineRenderer rope = GetComponent(); // placing the floor object on the stage Instantiate(floorObject); // adjusting floor position floorObject.transform.position = new Vector2(0f, -2.2f); // adding the player to stage thePlayer = Instantiate(playerObject); // adjusting player position thePlayer.transform.position = new Vector2(0f, -1.8f); // generating 8 random walls for (int i = 0; i < 8; i++) { GameObject randomWall = Instantiate(wallObject); float screenWidth = Screen.width / 200; float screenHeight = Screen.height / 200; float randomX = Random.Range(-screenWidth, screenWidth); float randomY = Random.Range(-screenHeight / 2, screenHeight); randomWall.transform.position = new Vector2(randomX, randomY); } } // Update is called once per frame void Update () { // if mouse is pressed... if (Input.GetButtonDown ("Fire1")) { // this is how I fire a ray cast to check for objects under the mouse RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero); // if there's a collision and the colliding game object has been tagged as "Wall"... if (hit.collider != null && hit.collider.gameObject.CompareTag("Wall")) { // adding a distance joint to the player hookJoint = thePlayer.AddComponent() as DistanceJoint2D; // connecting the distance joint to the object under the mouse hookJoint.connectedBody = hit.collider.GetComponent(); // calculating the distance between the player and the object under the mouse float distance = Vector2.Distance(hit.transform.position, thePlayer.transform.position); // setting distance joint distance accordingly hookJoint.distance = distance; // objects connected by the joint can collide hookJoint.enableCollision = true; // this LineRenderer has two points, marked as “0” and “1”. Setting “0” points to wall position rope.SetPosition(0, hit.transform.position); } } // if mouse is released… if (Input.GetButtonUp(“Fire1”)) { // if there is a distance joint… if (hookJoint) { // destroying the joint Destroy(hookJoint); // setting hookJoint variable to null hookJoint = null; // setting “0” and “1” points in the same position will cause the rope not to render rope.SetPosition(0, new Vector3(0, 0, 0)); rope.SetPosition(1, new Vector3(0, 0, 0)); } } // if there is a distance joint… if (hookJoint) { // shorten its distance by 0.05% hookJoint.distance = hookJoint.distance * 0.995f; // setting “1” points of rope LineRenderer to player position, causing the rope to be displayed rope.SetPosition(1, thePlayer.transform.position); } } }
As you can see, it’s very easy to create a hook with Unity. As it was with other languages and frameworks. Give me feedback and Download the source code.

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