Monday, September 9, 2013

Unity Swipe Camera Rotation - FPS Controller (Part 1) for Touchscreen


Check out the finished code below the videos
  • 0:45 - Scene explaination and script planning
  • 1:45 - Starting the script, setting up variables and our function
  • 3:07 - Explaination of Euler Angles in Unity
  • 4:18 - Calculating our camera's pitch and yaw rotations
  • 5:58 - Working Demonstration in game
  • 6:30 - Invert look option
  • 7:55 - Limiting the up and down look rotation with Mathf.Clamp
  • 9:05 - Demonstration of clamped rotation
  • 9:25 - Using our script to rotate any game object
  • 10:05 - Setting up a Touchpad area on screen to limit the area you can use to rotate the camera
  • 13:13 - Outro - Describing Part 2 of our FPS controller where we'll make a joystick to control the player movement
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 SwipeRotationPlayer : TouchLogicV2//NOTE: This script has been updated to V2 after video recording
{
 public float rotateSpeed = 100.0f;
 public int invertPitch = 1;
 public Transform player;
 private float pitch = 0.0f,
 yaw = 0.0f;
 //cache initial rotation of player so pitch and yaw don't reset to 0 before rotating
 private Vector3 oRotation;

 void Start()
 {
  //cache original rotation of player so pitch and yaw don't reset to 0 before rotating
  oRotation = player.eulerAngles;
  pitch = oRotation.x;
  yaw = oRotation.y;
 }

 public override void OnTouchBegan()
 {
  //need to cache the touch index that started on the pad so others wont interfere
  touch2Watch = TouchLogicV2.currTouch;
 }
 public override void OnTouchMoved()
 {
  pitch -= Input.GetTouch(touch2Watch).deltaPosition.y * rotateSpeed * invertPitch * Time.deltaTime;
  yaw += Input.GetTouch(touch2Watch).deltaPosition.x * rotateSpeed * invertPitch * Time.deltaTime;
  //limit so we dont do backflips
  pitch = Mathf.Clamp(pitch, -80, 80);
  //do the rotations of our camera
  player.eulerAngles = new Vector3 ( pitch, yaw, 0.0f);
 }

 public override void OnTouchEndedAnywhere()
 {
  //the || condition is a failsafe
  if(TouchLogicV2.currTouch == touch2Watch || Input.touches.Length <= 0)
   touch2Watch = 64;
 }
}