I am building a top down shooter for android, the game itself is 3D I just have the camera looking straight down. I would like to adapt my current script to work with a single joystick instead of the arrow keys. I need it to make the character smoothly face the direction of the joystick and move in that direction. Please Help and thank you in advance!!
My script:
using UnityEngine;
using System.Collections;
//Reference to Unity CharacterController
[RequireComponent (typeof(CharacterController))]
public class PlayerController : MonoBehaviour {
//Instance of the CharacterController
private CharacterController controller;
//Where is it we want the player to face
private Quaternion targetRotation;
//What speed do we want player to rotate towards target direction
public float rotationSpeed = 500;
//Speed variables for the player
public float walkSpeed = 5;
public float runSpeed = 8;
public Gun gun;
//Starts when object that script is atached is initialized
void Start () {
//Sets Up CharacterController
controller = GetComponent<CharacterController> ();
}
//Similiar to Greenfoot act method
void Update () {
//Sets a vector3 = to the input on the WASD and Arrow Keys
Vector3 input = new Vector3 (Input.GetAxisRaw ("Horizontal"), 0,
Input.GetAxisRaw ("Vertical"));
//Set rotation of Player
if (input != Vector3.zero) {
targetRotation = Quaternion.LookRotation (input);
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y,
targetRotation.eulerAngles.y - 1, rotationSpeed * Time.deltaTime);
}
Vector3 motion = input;
//If the player is going diagonally, this line will make it so that it moves 1 unit
//instead of aprox. 1.4 units. That is because a right triangle where x = 1, y = 1, and
//the hyponuse is square root of 2 or aprox. 1.4 units.
motion *= (Mathf.Abs (input.x) == 1 && Mathf.Abs (input.z) == 1) ? .7f : 1;
//Check to see if run key (left shift) is pressed, if so run, if not walk
motion *= (Input.GetButton ("run")) ? runSpeed : walkSpeed;
//Apply Gravity
motion += Vector3.up * -8;
//Set movement for player
controller.Move (motion * Time.deltaTime);
if (Input.GetButtonDown ("Shoot")) {
gun.Shoot ();
} else if (Input.GetButton ("Shoot")) {
gun.ShootContinuously();
}
}
}