- Home /
How to achieve a stable hover
In the game that I am currently making the play character is supposed to hover off the ground. I had used the code from the Hover Car tutorial on the unity website however this causes a lot of fluctuation in height even when staying still on a flat surface. This is a problem because the game is supposed to be in the first person. Is there a way to make the player character more stable?
public float hoverForce = 65f;
public float hoverHeight = 3.5f;
public Rigidbody playerRB;
// Start is called before the first frame update
void Start()
{
playerRB = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
Ray ray = new Ray(transform.position, -transform.up);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, hoverHeight))
{
float proportionalHeight = (hoverHeight - hit.distance) / hoverHeight;
Vector3 appliedHoverForce = Vector3.up * proportionalHeight * hoverForce;
playerRB.AddForce(appliedHoverForce, ForceMode.Acceleration);
}
}
Answer by RSWL51_ · Apr 15 at 12:28 PM
Heyo, I know this is an old question but as I stumbled upon that myself and did not find any satisfying solutions, I figured it out.
Here you go:
//distance being the distance to the ground
//hoverpower being an adjustable variable
Code to hover:
if (distance < internalHoverHeight) {
rigidbody.AddForce(groundNormal * hoverPower * (1 - (distance/internalHoverHeight)), ForceMode.Acceleration);
}
//hoverDampen being an adjustable variable
Code to dampen:
Vector3 vel = rigidbody.velocity;
Vector3 momentumUp = Vector3.Project(vel, groundNormal);
rigidbody.velocity = vel - momentumUp * hoverDampen;
This basically subtracts a fraction of the velocity in your upwards direction from the velocity. A hoverDampen value of 1 would set the velocity in upwards direction to zero.
cheers :P
Your answer

Follow this Question
Related Questions
4.6 UI Hover & Click sound? 1 Answer
How do I make a crosshair? 2 Answers
Hovering smoothly at one height 1 Answer
Need help with my hovercraft vehicle 0 Answers
FPS Controller Confusion... 0 Answers