Advertisement
Guest User

AimingRig CharacterMovementNoCamera Update

a guest
Jul 29th, 2020
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.10 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. // WASD to move, Space to sprint
  4. public class CharacterMovementNoCamera : MonoBehaviour
  5. {
  6.     public Transform InvisibleCameraOrigin;
  7.  
  8.     public float StrafeSpeed = 0.1f;
  9.     public float TurnSpeed = 3;
  10.     public float Damping = 0.2f;
  11.     public float VerticalRotMin = -80;
  12.     public float VerticalRotMax = 80;
  13.     public KeyCode sprintJoystick = KeyCode.JoystickButton2;
  14.     public KeyCode sprintKeyboard = KeyCode.Space;
  15.  
  16.     private bool isSprinting;
  17.     private Animator anim;
  18.     private float currentStrafeSpeed;
  19.     private Vector2 currentVelocity;
  20.  
  21.     void OnEnable()
  22.     {
  23.         anim = GetComponent<Animator>();
  24.         currentVelocity = Vector2.zero;
  25.         currentStrafeSpeed = 0;
  26.         isSprinting = false;
  27.     }
  28.  
  29.     void Update()
  30.     {
  31.         var rotInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
  32.         var rot = transform.eulerAngles;
  33.         rot.y += rotInput.x * TurnSpeed;
  34.         transform.rotation = Quaternion.Euler(rot);
  35.  
  36.         if (InvisibleCameraOrigin != null)
  37.         {
  38.             rot = InvisibleCameraOrigin.localRotation.eulerAngles;
  39.             rot.x -= rotInput.y * TurnSpeed;
  40.             if (rot.x > 180)
  41.                 rot.x -= 360;
  42.             rot.x = Mathf.Clamp(rot.x, VerticalRotMin, VerticalRotMax);
  43.             InvisibleCameraOrigin.localRotation = Quaternion.Euler(rot);
  44.         }
  45.     }
  46.  
  47.     void FixedUpdate()
  48.     {
  49.         var input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
  50.         var speed = input.y;
  51.         speed = Mathf.Clamp(speed, -1f, 1f);
  52.         speed = Mathf.SmoothDamp(anim.GetFloat("Speed"), speed, ref currentVelocity.y, Damping);
  53.         anim.SetFloat("Speed", speed);
  54.         anim.SetFloat("Direction", speed);
  55.  
  56.         // set sprinting
  57.         isSprinting = (Input.GetKey(sprintJoystick) || Input.GetKey(sprintKeyboard)) && speed > 0;
  58.         anim.SetBool("isSprinting", isSprinting);
  59.  
  60.         // strafing
  61.         currentStrafeSpeed = Mathf.SmoothDamp(
  62.             currentStrafeSpeed, input.x * StrafeSpeed, ref currentVelocity.x, Damping);
  63.         transform.position += transform.TransformDirection(Vector3.right) * currentStrafeSpeed;
  64.     }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement