maxhacker11

PlayerMovement.cs

Sep 3rd, 2023
3,033
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 KB | Source Code | 0 0
  1. using UnityEngine;
  2.  
  3. public class PlayerMovement : MonoBehaviour
  4. {
  5.     private float horizontal;
  6.     private float speed = 8f;
  7.     private float jumpingPower = 16f;
  8.     private bool isFacingRight = true;
  9.  
  10.     private Collider2D platformCollider;
  11.  
  12.     [SerializeField] private Rigidbody2D rb;
  13.     [SerializeField] private Transform groundCheck;
  14.     [SerializeField] private LayerMask groundLayer;
  15.  
  16.     void Update()
  17.     {
  18.         horizontal = Input.GetAxisRaw("Horizontal");
  19.  
  20.         if (Input.GetButtonDown("Jump") && IsGrounded())
  21.         {
  22.             rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
  23.         }
  24.  
  25.         if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
  26.         {
  27.             rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
  28.         }
  29.  
  30.         Flip();
  31.     }
  32.  
  33.     private void FixedUpdate()
  34.     {
  35.         rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
  36.     }
  37.  
  38.     private bool IsGrounded()
  39.     {
  40.         return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
  41.     }
  42.  
  43.     private void Flip()
  44.     {
  45.         if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
  46.         {
  47.             isFacingRight = !isFacingRight;
  48.             Vector3 localScale = transform.localScale;
  49.             localScale.x *= -1f;
  50.             transform.localScale = localScale;
  51.         }
  52.     }
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment