2D player Movement | Unit 10

PHOTO EMBED

Tue May 17 2022 18:33:32 GMT+0000 (UTC)

Saved by @BiscuitTinx #c#

using UnityEngine;
using UnityEngine.UI;

public class PlayerScript : MonoBehaviour
{
    [SerializeField]
    private float fuel = 100f;
    [SerializeField]
    private Slider fuelSlider;
    [SerializeField]
    private float fuelBurnRate = 20f;
    
    private float currentFuel;

    public float MovementSpeed = 1;
    public float JumpForce = 1;

    public Animator jetpackEffect;

    bool regenFuel;

    private Rigidbody2D _rigidbody;
    // Start is called before the first frame update
   private void Start()
    {
        _rigidbody = GetComponent<Rigidbody2D>();

        currentFuel = fuel;
    }

    // Update is called once per frame
    private void FixedUpdate()
    {
        var movement = Input.GetAxis("Horizontal");
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
    }

    private void Update()
    {

        fuelSlider.value = currentFuel / fuel;

        if (Input.GetButton("Jump") && currentFuel > 0)// && Mathf.Abs(_rigidbody.velocity.y) < 0.001f)
        {
            _rigidbody.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
            jetpackEffect.SetBool("Fly", true);
            currentFuel -= fuelBurnRate * Time.deltaTime;
        } else
        {
            jetpackEffect.SetBool("Fly", false);

            if (regenFuel && currentFuel < 100)
            {
                currentFuel += fuelBurnRate * Time.deltaTime;
            }
        }  
    }

    private void OnCollisionEnter2D(Collision2D c)
    {
        if(c.gameObject.tag == "Ground")
        {
            regenFuel = true;
        }
    }

    private void OnCollisionExit2D(Collision2D c)
    {
        if (c.gameObject.tag == "Ground")
        {
            regenFuel = false;
        }
    }
}
content_copyCOPY