Monday, November 25, 2013

Unity Touch Follow Tutorial

This Unity C# tutorial will show you how to make a game object look at and follow your touch.


Time Breakdown
  • 0:00 - Thank you!
  • 0:27 - Technical Difficulties with Youtube
  • 1:55 - Overview of what we're doing. Making an object follow your touch on screen
  • 2:40 - Important note about the orientation of your character or object
  • 3:25 - Inheiriting from TouchLogic and setting up variables
  • 5:00 - Setting up our function definitions
  • 7:40 - Setting our finger vector with ScreenToWorldPoint
  • 8:00 - Setting up a temp variable with a z value appended to our touch position
  • 9:25 - Going to the Unity Scripting Documentation to see what we need the z value for
  • 9:44 - Calculating that z value
  • 10:46 - Make our object LookAt our finger
  • 11:15 - Demonstration of the objects looking at our finger in Unity
  • 11:40 - Make the object move towards our finger
  • 12:50 - Demonstration of the object moving towards our finger
  • 13:16 - Outro, thanks for watching
Check out the videos above to hear the explanation and see the code in action
/*/
* Script by Devin Curry
* www.Devination.com
* www.youtube.com/user/curryboy001
* Please like and subscribe if you found my tutorials helpful :D
* Twitter: https://twitter.com/Devination3D
/*/
using UnityEngine;
using System.Collections;

public class FollowTouch : TouchLogicV2//NOTE: This script has been updated to V2 after video recording
{
 public float speed = 1f, maxDist = 2;
 private Vector3 finger;
 private Transform myTrans, camTrans;
 
 void Start ()
 {
  myTrans = this.transform;
  camTrans = Camera.main.transform;
 }
 
 //separated to own function so it can be called from multiple functions
 void LookAtFinger()
 {
  //z of ScreenToWorldPoint is distance from camera into the world, so we need to find this object's distance from the camera to make it stay on the same plane
  Vector3 tempTouch = new Vector3(Input.GetTouch(touch2Watch).position.x, Input.GetTouch(touch2Watch).position.y,camTrans.position.y - myTrans.position.y);
  //Convert screen to world space
  finger = Camera.main.ScreenToWorldPoint(tempTouch);
  
  //look at finger position
  myTrans.LookAt(finger);
  
  //move towards finger if not too close
  if(Vector3.Distance(finger, myTrans.position) > maxDist)
   myTrans.Translate (Vector3.forward * speed * Time.deltaTime);
 }
 public override void OnTouchMovedAnywhere()
 {
  LookAtFinger();
 }
 public override void OnTouchStayedAnywhere()
 {
  LookAtFinger();
 }
 public override void OnTouchBeganAnywhere()
 {
  touch2Watch = TouchLogicV2.currTouch;
 }
}