Advertisement
apencer1w

Character Controller

Dec 21st, 2016
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class CharacterController : MonoBehaviour
  5. {
  6.  
  7.     public float mouseSpeedX;
  8.     public float mouseSpeedY;
  9.     public float playerMoveSpeed;
  10.     public float jumpForce;
  11.  
  12.     float verticalLookRotation;
  13.     Rigidbody rb;
  14.     Ray ray;
  15.  
  16.     bool isGrouded() {
  17.         Vector3 pos = transform.position; pos.y -= 0.98f;
  18.         Collider[] cols = Physics.OverlapSphere(pos, 0.2f);
  19.         if (cols.Length > 1) return true;
  20.         else return false;
  21.     }
  22.  
  23.     void Start() {
  24.         Cursor.lockState = CursorLockMode.Locked;
  25.         Cursor.visible = false;
  26.         rb = GetComponent<Rigidbody>();
  27.     }
  28.  
  29.     void Update() {
  30.  
  31.         if (Input.GetKeyDown(KeyCode.Escape)) {
  32.             Cursor.lockState = CursorLockMode.None;
  33.             Cursor.visible = true;
  34.         }
  35.         if (Input.GetMouseButtonDown(0)) {
  36.             Cursor.lockState = CursorLockMode.Locked;
  37.             Cursor.visible = false;
  38.         }
  39.         Camera.main.transform.localPosition = new Vector3(0f, 0.75f, 0f);
  40.         transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * Time.deltaTime * mouseSpeedX);
  41.         verticalLookRotation += Input.GetAxis("Mouse Y") * Time.deltaTime * mouseSpeedY;
  42.         verticalLookRotation = Mathf.Clamp(verticalLookRotation, -90, 75);
  43.         Camera.main.transform.localEulerAngles = Vector3.left * verticalLookRotation;
  44.  
  45.         rb.velocity = new Vector3(0f, rb.velocity.y, 0f);
  46.         float finalMoveSpeed = (Input.GetKey(KeyCode.LeftShift)) ? playerMoveSpeed * 1.5f : playerMoveSpeed;
  47.  
  48.         Vector3 movement = transform.TransformDirection(new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")).normalized);
  49.        
  50.         rb.MovePosition(transform.position + movement * finalMoveSpeed);
  51.        
  52.         if (Input.GetKey(KeyCode.Space) && isGrouded()) rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement