Advertisement
CaptainSpaceCat

PlayerController Generic

Aug 13th, 2015
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.75 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class PlayerController : MonoBehaviour {
  5.  
  6.     private float xDir = 0;
  7.     private float yDir = 0;
  8.     private Rigidbody rigidbody;
  9.     private bool controlsLocked = true;
  10.    
  11.     public float speed;
  12.     [RangeAttribute (1, 10)]
  13.     public float sensitivity;
  14.  
  15.     void Start() {
  16.         rigidbody = GetComponent<Rigidbody> ();
  17.         rigidbody.freezeRotation = true;
  18.         Cursor.lockState = CursorLockMode.None;
  19.         Cursor.visible = true;
  20.     }
  21.    
  22.     void FixedUpdate () {
  23.  
  24.         if (!controlsLocked) {
  25.        
  26.             if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.D)) {
  27.                 rigidbody.velocity = transform.right * speed;
  28.             }
  29.             if (Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A)) {
  30.                 rigidbody.velocity = -transform.right * speed;
  31.             }
  32.             if (Input.GetKey (KeyCode.UpArrow) || Input.GetKey (KeyCode.W)) {
  33.                 rigidbody.velocity = transform.forward * speed;
  34.             }
  35.             if (Input.GetKey (KeyCode.DownArrow) || Input.GetKey (KeyCode.S)) {
  36.                 rigidbody.velocity = -transform.forward * speed;
  37.             }
  38.             if (Input.GetKey (KeyCode.Space)) {
  39.                 rigidbody.velocity = transform.up * speed;
  40.             }
  41.             if (Input.GetKey (KeyCode.LeftShift)) {
  42.                 rigidbody.velocity = -transform.up * speed;
  43.             }
  44.        
  45.             xDir += Input.GetAxis ("Mouse X") * sensitivity;
  46.             yDir -= Input.GetAxis ("Mouse Y") * sensitivity;
  47.  
  48.             rigidbody.rotation = Quaternion.Euler (yDir, xDir, 0.0f);
  49.         }
  50.     }
  51.  
  52.     void LockControls() {
  53.         controlsLocked = true;
  54.         Cursor.lockState = CursorLockMode.None;
  55.         Cursor.visible = true;
  56.     }
  57.  
  58.     void FreeControls() {
  59.         controlsLocked = false;
  60.         Cursor.lockState = CursorLockMode.Locked;
  61.         Cursor.visible = false;
  62.     }
  63.  
  64.     void ResetPosition() {
  65.         rigidbody.position = new Vector3 (-2, -2, -2);
  66.         xDir = 0;
  67.         yDir = 0;
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement