Advertisement
tommarek_CZE

Movement Code

Jan 22nd, 2022
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.28 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class PlayerController : MonoBehaviour
  6. {
  7.     [SerializeField] Transform playerCamera = null;
  8.     [SerializeField] float mouseSensitivity = 3.5f;
  9.     [SerializeField] float walkSpeed = 6.0f;
  10.     [SerializeField] float gravity = -13.0f;
  11.     [SerializeField][Range(0.0f, 0.5f)] float moveSmoothTime = 0.3f;
  12.     [SerializeField][Range(0.0f, 0.5f)] float mouseSmoothTime = 0.03f;
  13.  
  14.     [SerializeField] bool lockCursor = true;
  15.  
  16.     float cameraPitch = 0.0f;
  17.     float velocityY = 0.0f;
  18.     CharacterController controller = null;
  19.  
  20.     Vector2 currentDir = Vector2.zero;
  21.     Vector2 currentDirVelocity = Vector2.zero;
  22.  
  23.     Vector2 currentMouseDelta = Vector2.zero;
  24.     Vector2 currentMouseDeltaVelocity = Vector2.zero;
  25.  
  26.     void Start()
  27.     {
  28.         controller = GetComponent<CharacterController>();
  29.         if(lockCursor)
  30.         {
  31.             Cursor.lockState = CursorLockMode.Locked;
  32.             Cursor.visible = false;
  33.         }
  34.     }
  35.  
  36.     void Update()
  37.     {
  38.         UpdateMouseLook();
  39.         UpdateMovement();
  40.     }
  41.  
  42.     void UpdateMouseLook()
  43.     {
  44.         Vector2 targetMouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
  45.  
  46.         currentMouseDelta = Vector2.SmoothDamp(currentMouseDelta, targetMouseDelta, ref currentMouseDeltaVelocity, mouseSmoothTime);
  47.  
  48.         cameraPitch -= currentMouseDelta.y * mouseSensitivity;
  49.         cameraPitch = Mathf.Clamp(cameraPitch, -90.0f, 90.0f);
  50.  
  51.         playerCamera.localEulerAngles = Vector3.right * cameraPitch;
  52.         transform.Rotate(Vector3.up * currentMouseDelta.x * mouseSensitivity);
  53.     }
  54.  
  55.     void UpdateMovement()
  56.     {
  57.         Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
  58.         targetDir.Normalize();
  59.            
  60.         currentDir = Vector2.SmoothDamp(currentDir, targetDir, ref currentDirVelocity, moveSmoothTime);
  61.  
  62.         if(controller.isGrounded)
  63.             velocityY = 0.0f;
  64.  
  65.         velocityY += gravity * Time.deltaTime;
  66.        
  67.         Vector3 velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * walkSpeed + Vector3.up * velocityY;
  68.  
  69.         controller.Move(velocity * Time.deltaTime);
  70.  
  71.  
  72.    
  73.     }
  74.  
  75.  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement