Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using System.Numerics; // Only if necessary for other parts of the script
- using UnityEngine;
- using UnityEngine.InputSystem;
- public class PlayerMovement : MonoBehaviour
- {
- [SerializeField] private float speed;
- [SerializeField] private float rotationSpeed;
- [SerializeField] private float screenBorder;
- private Rigidbody2D rigidbody;
- private UnityEngine.Vector2 movementInput;
- private UnityEngine.Vector2 smoothedMovementInput;
- private UnityEngine.Vector2 movementInputSmoothVelocity;
- private Camera camera;
- private Animator animator;
- private void Awake()
- {
- rigidbody = GetComponent<Rigidbody2D>();
- camera = Camera.main;
- animator = GetComponent<Animator>();
- }
- private void FixedUpdate()
- {
- SetPlayerVelocity();
- RotateInDirectionOfInput();
- SetAnimation();
- }
- private void SetAnimation()
- {
- bool isMoving = movementInput != UnityEngine.Vector2.zero;
- animator.SetBool("isMoving", isMoving);
- }
- private void SetPlayerVelocity()
- {
- smoothedMovementInput = UnityEngine.Vector2.SmoothDamp(smoothedMovementInput, movementInput, ref movementInputSmoothVelocity, 0.1f);
- rigidbody.velocity = smoothedMovementInput * speed;
- PreventPlayerGoingOffScreen();
- }
- private void PreventPlayerGoingOffScreen()
- {
- UnityEngine.Vector2 screenPosition = camera.WorldToScreenPoint(transform.position);
- if ((screenPosition.x < screenBorder && rigidbody.velocity.x < 0) || (screenPosition.x > camera.pixelWidth - screenBorder && rigidbody.velocity.x > 0))
- {
- rigidbody.velocity = new UnityEngine.Vector2(0, rigidbody.velocity.y);
- }
- if ((screenPosition.y < screenBorder && rigidbody.velocity.y < 0) || (screenPosition.y > camera.pixelHeight - screenBorder && rigidbody.velocity.y > 0))
- {
- rigidbody.velocity = new UnityEngine.Vector2(rigidbody.velocity.x, 0);
- }
- }
- private void RotateInDirectionOfInput()
- {
- if (movementInput != UnityEngine.Vector2.zero)
- {
- UnityEngine.Quaternion targetRotation = UnityEngine.Quaternion.LookRotation(transform.forward, smoothedMovementInput);
- UnityEngine.Quaternion rotation = UnityEngine.Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
- rigidbody.MoveRotation(rotation);
- }
- }
- private void OnMove(InputValue inputValue)
- {
- movementInput = inputValue.Get<UnityEngine.Vector2>();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement