Advertisement
leomovskii

PlayerMove2D

Oct 25th, 2024
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.08 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class PlayerMove2D : MonoBehaviour {
  4.  
  5.     public float moveSpeed = 5f;
  6.     public float jumpPower = 5f;
  7.     public int jumpsLimit = 2;
  8.  
  9.     Rigidbody2D _rigidbody;
  10.     int _jumpsDone;
  11.     float _horizontalInput;
  12.     bool _wantToJump;
  13.  
  14.     private void Start() {
  15.         _rigidbody = GetComponent<Rigidbody2D>();
  16.     }
  17.  
  18.     private void Update() {
  19.         _horizontalInput = Input.GetAxis("Horizontal") * moveSpeed; // -1 .. 1
  20.  
  21.         if (Input.GetButtonDown("Jump")) {
  22.             _wantToJump = true;
  23.         }
  24.  
  25.         if (_horizontalInput > 0) {
  26.             transform.localEulerAngles = new Vector3(0f, 0f, 0f);
  27.         } else if (_horizontalInput < 0) {
  28.             transform.localEulerAngles = new Vector3(0f, 180f, 0f);
  29.         }
  30.     }
  31.  
  32.     private void FixedUpdate() { // 0.02
  33.         if (_wantToJump && _jumpsDone < jumpsLimit) { // true/false
  34.             _rigidbody.velocity = new Vector2(_horizontalInput, jumpPower);
  35.             _jumpsDone++;
  36.  
  37.         } else {
  38.             _rigidbody.velocity = new Vector2(_horizontalInput, _rigidbody.velocity.y);
  39.         }
  40.  
  41.         _wantToJump = false;
  42.     }
  43.  
  44.     private void OnCollisionEnter2D(Collision2D collision) {
  45.         _jumpsDone = 0;
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement