Advertisement
GigaOrts

Player

May 18th, 2025
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.15 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. namespace Scripts28785
  4. {
  5.     public class Player : MonoBehaviour
  6.     {
  7.         private const string Horizontal = "Horizontal";
  8.         private const string Vertical = "Vertical";
  9.         private const string RunMultiplier = "RunMultiplier";
  10.         private const string Run = "Run";
  11.         private readonly float _defaultSpeed = 1f;
  12.  
  13.         private Rigidbody2D _body2D;
  14.         private Animator _animator;
  15.         public float _speed = 3f;
  16.         private Camera _camera;
  17.         private Vector3 _faceDirection;
  18.  
  19.         private void Awake()
  20.         {
  21.             _body2D = GetComponent<Rigidbody2D>();
  22.             _animator = GetComponent<Animator>();
  23.         }
  24.  
  25.         private void Start()
  26.         {
  27.             _camera = Camera.main;
  28.         }
  29.    
  30.         private void Update()  
  31.         {  
  32.             RotateCharacter();  
  33.         }  
  34.  
  35.         private void RotateCharacter()  
  36.         {  
  37.             Vector3 mousePosition = Input.mousePosition;  
  38.  
  39.             Vector3 worldMousePosition = _camera.ScreenToWorldPoint(mousePosition);  
  40.          
  41.             _faceDirection = worldMousePosition - transform.position;  
  42.  
  43.             if (_faceDirection.x < 0)  
  44.             {  
  45.                 transform.rotation = Quaternion.Euler(0, 180,0);
  46.             }  
  47.             else  
  48.             {  
  49.                 transform.rotation = Quaternion.Euler(0, 0,0);
  50.             }  
  51.         }  
  52.    
  53.         private void FixedUpdate()
  54.         {
  55.             Vector2 velocity = new Vector2(
  56.                 Input.GetAxisRaw(Horizontal),
  57.                 Input.GetAxisRaw(Vertical));
  58.  
  59.             bool isRunning = velocity.magnitude > 0;
  60.             _animator.SetBool(Run, isRunning);
  61.  
  62.             if ((_faceDirection.x < 0 && velocity.x > 0) ||
  63.                 (_faceDirection.x > 0 && velocity.x < 0) && isRunning)
  64.             {
  65.                 _animator.SetFloat(RunMultiplier, -_defaultSpeed);
  66.             }
  67.             else
  68.             {
  69.                 _animator.SetFloat(RunMultiplier, _defaultSpeed);
  70.             }
  71.        
  72.             _body2D.velocity = velocity.normalized * _speed;
  73.         }
  74.     }
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement