jahedev

Movement.cs

Mar 28th, 2022
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Movement : MonoBehaviour
  6. {
  7.     [SerializeField] float movement;
  8.     [SerializeField] Rigidbody2D rigid;
  9.     [SerializeField] int speed;
  10.     [SerializeField] bool isFacingRight = true;
  11.     [SerializeField] bool jumpPressed = false;
  12.     [SerializeField] float jumpForce = 500.0f;
  13.     [SerializeField] bool isGrounded = true;
  14.     [SerializeField] bool shiftPressed = false;
  15.  
  16.     // Start is called before the first frame update
  17.     void Start()
  18.     {
  19.         if (rigid == null)
  20.             rigid = GetComponent<Rigidbody2D>();
  21.         speed = 15;
  22.     }
  23.  
  24.     // Update is called once per frame
  25.     void Update()
  26.     {
  27.         movement = Input.GetAxis("Horizontal");
  28.         if (Input.GetButtonDown("Jump"))
  29.             jumpPressed = true;
  30.        
  31.     }
  32.  
  33.     //called potentially multiple times per frame
  34.     //used for physics & movement
  35.     void FixedUpdate()
  36.     {
  37.         rigid.velocity = new Vector2(movement * speed, rigid.velocity.y);
  38.         if (movement < 0 && isFacingRight || movement > 0 && !isFacingRight)
  39.             Flip();
  40.         if (jumpPressed && isGrounded)
  41.             Jump();
  42.     }
  43.  
  44.     void Flip()
  45.     {
  46.         transform.Rotate(0, 180, 0);
  47.         isFacingRight = !isFacingRight;
  48.     }
  49.  
  50.     void Jump()
  51.     {
  52.         rigid.velocity = new Vector2(rigid.velocity.x, 0);
  53.         rigid.AddForce(new Vector2(0, jumpForce));
  54.         isGrounded = false;
  55.         jumpPressed = false;
  56.     }
  57.  
  58.     private void OnCollisionEnter2D(Collision2D collision)
  59.     {
  60.         if (collision.gameObject.tag == "Ground")
  61.         {
  62.             isGrounded = true;
  63.         }
  64.     }
  65.  
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment