How to make it so I can't use the jetpack/jump while slider value is 0?
I have 2 scripts, the fuel script and the movement and camera script. I know why it's not working, I just have no idea how to fix it. The problem is that when I'm holding down space, it initiates the if statement while the slider value is greater then 0, but once the slider reaches 0 the if statement is still running so I can infinitely fly.
Movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class MovementAndCamera : MonoBehaviour
{
public float speed;
public bool onGround;
public Rigidbody rb;
public Collider rbCollider;
public float distanceToGround;
public static bool jumpKey;
public Slider fuelBar;
public bool noFuel;
public Camera playerCamera;
public float mouseSensitivity = 4.0f;
public float lookSpeed = 2.0f;
public float lookXLimit = 90f;
private float rotationX;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
rbCollider = GetComponent<Collider>();
speed = 5f;
Cursor.lockState = CursorLockMode.Locked;
noFuel = false;
}
// Update is called once per frame
void Update()
{
distanceToGround = rbCollider.bounds.extents.y;
bool onGround = Physics.Raycast(transform.position, Vector3.down, distanceToGround);
//Debug.Log(onGround);
jumpKey = Input.GetKey(KeyCode.Space);
//Debug.Log(jumpKey);
CameraAiming();
Movement();
//Debug.Log(Time.deltaTime);
}
void CameraAiming()
{
rotationX += -Input.GetAxis("Mouse Y") * mouseSensitivity;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
void Movement()
{
if(Input.GetKey(KeyCode.W)) {
rb.AddForce(transform.forward * speed);
}
if(Input.GetKey(KeyCode.S)) {
rb.AddForce(-transform.forward * speed);
}
if(Input.GetKey(KeyCode.A)) {
rb.AddForce(Vector3.left * speed);
}
if(Input.GetKey(KeyCode.D)) {
rb.AddForce(Vector3.right * speed);
}
if (fuelBar.value <= 0) {
noFuel = true;
}
if(noFuel != true & jumpKey) {
rb.AddForce(new Vector3(0, 30, 0));
}
}
}
Fuel script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class FuelSystem : MonoBehaviour
{
public float fuel = 100;
public float currentFuel;
public float dischargeTime = 10f;
public float rechargeTime = 0.00f;
public Slider fuelBar;
public static bool jumpKey;
// Start is called before the first frame update
void Start()
{
fuelBar = GetComponent<Slider>();
currentFuel = fuel;
}
// Update is called once per frame
void Update() {
jumpKey = Input.GetKey(KeyCode.Space);
if (jumpKey == true) {
currentFuel = Mathf.Lerp(currentFuel, 0, dischargeTime * Time.deltaTime);
fuelBar.value = currentFuel;
}
if (jumpKey == false) {
currentFuel = Mathf.Lerp(currentFuel, fuel, rechargeTime * Time.deltaTime);
fuelBar.value = currentFuel;
}
}
}
Comment