- using System.Collections;
- using System.Collections.Generic;
- using System.Threading;
- using UnityEngine;
- public class PlayerController : MonoBehaviour
- {
- private Rigidbody rb;
- private Vector2 currentVelocity;
- private Vector2 targetVelocity;
- private Animator animator;
- [SerializeField] private bool crouch = false;
- [SerializeField] private bool canCrouchCover = false;
- [SerializeField] private float rotationSpeed = 5f;
- [SerializeField] private float movementSmoothing = 0.1f;
- public float smoothing = 0.1f;
- private float currentTurnValue;
- private float turnVelocity;
- private void Awake()
- {
- rb = GetComponent<Rigidbody>();
- animator = GetComponent<Animator>();
- }
-
- void Start()
- {
- animator.applyRootMotion = true;
- }
-
- void Update()
- {
- IsCrouched();
- ApplyRotation();
-
- float horizontal = Input.GetAxis("Horizontal");
- float vertical = Input.GetAxis("Vertical");
-
- if (IsRunning())
- {
-
- targetVelocity = new Vector2(horizontal, vertical) * 2f;
- }
- else
- {
-
- targetVelocity = new Vector2(horizontal, vertical);
- }
-
- currentVelocity = Vector2.Lerp(currentVelocity, targetVelocity, movementSmoothing);
-
- animator.SetFloat("Horizontal", currentVelocity.x);
- animator.SetFloat("Vertical", currentVelocity.y);
-
-
-
-
- animator.SetBool("Crouched", crouch);
- animator.SetBool("CrouchCover", canCrouchCover);
- }
-
- private bool IsRunning() => Input.GetKey(KeyCode.LeftShift) ? true : false;
- private void IsCrouched()
- {
- if (Input.GetKeyDown(KeyCode.LeftControl))
- {
- crouch = !crouch;
- }
- }
- void OnCollisionStay(Collision collision)
- {
- if (Input.GetKeyDown(KeyCode.Q))
- {
- Debug.Log("COLLISION!");
- foreach (ContactPoint contact in collision.contacts)
- {
- if (contact.otherCollider.tag == "SmallWall") canCrouchCover = !canCrouchCover;
- break;
- }
- }
- }
- private void OnAnimatorMove()
- {
- Vector3 pos;
- if(canCrouchCover)
- {
- pos = new Vector3(transform.position.x, transform.position.y, animator.rootPosition.z);
- transform.position = pos;
- }
-
- else
- {
- transform.position = animator.rootPosition;
- transform.rotation = animator.rootRotation;
- }
- }
- void RotateCharacter(float turnValue)
- {
-
- animator.SetFloat("Turn", turnValue);
-
- transform.Rotate(Vector3.up, turnValue * rotationSpeed * Time.deltaTime);
- }
- void ApplyRotation()
- {
-
- float mouseX = Input.GetAxis("Mouse X");
-
- float targetTurnValue = mouseX;
-
- currentTurnValue = Mathf.Lerp(currentTurnValue, targetTurnValue, smoothing);
-
- if (mouseX != 0)
- {
- RotateCharacter(currentTurnValue);
- }
- else
- {
-
- currentTurnValue = Mathf.Lerp(currentTurnValue, 0, smoothing);
- animator.SetFloat("Turn", currentTurnValue);
- }
- }
- }