I am building a sidescroller game with a dragon that I want to fly. But instead of allowing the player to just constantly fly around the map, the dragon needs to be constrained to energy usage. I have the UI Slider reacting to his flight but when the value hits zero I want velocity to be cut off until the energy bar has enough energy to take flight again. So I have built a separate script to control the flight, energy usage, what happens when the energy hits zero and when he is on the ground to regain that energy slowly. I am pretty sure I am approaching this correctly however the code structure is incorrect and I would very much appreciate if someone can take a look and tell me what I need to change please.
public class Flight : MonoBehaviour
{
public KeyCode jumpButton;
public float jumpForce;
public UnityEngine.UI.Slider slider;
public float energyDecay;
public float energyRestore;
float energy;
const float maxEnergy = 100;
bool grounded;
Rigidbody rb;
void Start()
{
energy = slider.value;
slider.maxValue = maxEnergy;
slider.value = maxEnergy;
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKey(jumpButton) && energy <= maxEnergy)
{
Jump();
}
else if (energy <= 5f)
{
GetComponent<Rigidbody>().velocity = Vector3.zero;
}
}
private void FixedUpdate()
{
if (grounded)
{
slider.value += Time.deltaTime * energyRestore;
}
}
void Jump()
{
if (Input.GetKey(jumpButton))
{
rb.velocity = Vector3.up;
rb.AddForce(new Vector3(0, jumpForce));
slider.value -= Time.deltaTime * energyDecay;
}
}
void OnCollisionEnter(Collision col)
{
if (col.collider.tag == "Ground")
{
grounded = true;
}
}
void OnCollisionExit(Collision col)
{
if (col.collider.tag == "Ground")
{
grounded = false;
}
}
}
I’m confused with your jump condition.
In the Update() you check this: if (Input.GetKey(jumpButton) && energy <= maxEnergy) and in your jump function you check if (Input.GetKey(jumpButton)).
Why are you checking for key down twice? and why the second time you don’t check the energy? Is the Jump function being called from somewhere else too? (Other than Update())
Also, the second condition else if (energy <= 5f) will never be called since energy is always less than maxEnergy.
If you want to stop player form Jump()ing when energy is not enough you should do this:
if (Input.GetKey(jumpButton) && energy >= requiredEnergyToJump)
requiredEnergyToJump is the minimum energy for Jump()ing. (you should set that).
OLD ANSWER
If you want to stop an object (velocity) check this answer out:
And here’s how to slow down an object (velocity) till it stops: