Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- namespace Scripts28785
- {
- public class Player : MonoBehaviour
- {
- private const string Horizontal = "Horizontal";
- private const string Vertical = "Vertical";
- private const string RunMultiplier = "RunMultiplier";
- private const string Run = "Run";
- private readonly float _defaultSpeed = 1f;
- private Rigidbody2D _body2D;
- private Animator _animator;
- public float _speed = 3f;
- private Camera _camera;
- private Vector3 _faceDirection;
- private void Awake()
- {
- _body2D = GetComponent<Rigidbody2D>();
- _animator = GetComponent<Animator>();
- }
- private void Start()
- {
- _camera = Camera.main;
- }
- private void Update()
- {
- RotateCharacter();
- }
- private void RotateCharacter()
- {
- Vector3 mousePosition = Input.mousePosition;
- Vector3 worldMousePosition = _camera.ScreenToWorldPoint(mousePosition);
- _faceDirection = worldMousePosition - transform.position;
- if (_faceDirection.x < 0)
- {
- transform.rotation = Quaternion.Euler(0, 180,0);
- }
- else
- {
- transform.rotation = Quaternion.Euler(0, 0,0);
- }
- }
- private void FixedUpdate()
- {
- Vector2 velocity = new Vector2(
- Input.GetAxisRaw(Horizontal),
- Input.GetAxisRaw(Vertical));
- bool isRunning = velocity.magnitude > 0;
- _animator.SetBool(Run, isRunning);
- if ((_faceDirection.x < 0 && velocity.x > 0) ||
- (_faceDirection.x > 0 && velocity.x < 0) && isRunning)
- {
- _animator.SetFloat(RunMultiplier, -_defaultSpeed);
- }
- else
- {
- _animator.SetFloat(RunMultiplier, _defaultSpeed);
- }
- _body2D.velocity = velocity.normalized * _speed;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement