# Hovering smoothly at one height

So, I’m trying to make my character hover in one place (2.5d platformer, by the way). I’ve successfully been able to complete the hovering portion through raycasting downwards to find out if the player is high enough off the ground (determined with a “hoverHeight” float), then using “AddForce” to push it up to that height. But now my problem is that the player floats downwards until it hits the floor, then hovers back up to the “hoverHeight”, then repeats. I want it to hover to the height, then stay there.

Here’s a snippet of the code.

``````var ray : Ray = Ray(transform.position, -Vector3.up);
var hit : RaycastHit;

if (Physics.Raycast(ray, hit, hoverHeight)) {
var proportionalHeight : float = (hoverHeight - hit.distance) / hoverHeight;
var appliedHoverForce : Vector3 = Vector3.up * proportionalHeight * hoverForce;
}
``````

I know this is kinda old but your post interested me so I tested out some script and finally came up with this. Hope it might help. I needed something like this for my game as well. I basically took your code and changed it to not only work properly like you wanted, but made it more optimized without so many calls on the memory. so thought id share it with you.

``````  using UnityEngine;
using System.Collections;

public class Hover : MonoBehaviour {

public float magnitude;
public float frequency;
private float offset;

private Transform thisT;
private float anchor;

void Start ()
{
thisT=transform;
anchor=thisT.localPosition.y;
offset=Random.Range(0, Mathf.PI);
}

void Update ()
{
float hover=magnitude*(1+Mathf.Sin(Time.time*frequency+offset));
thisT.localPosition=new Vector3(thisT.localPosition.x, anchor+hover, thisT.localPosition.z);
}
}
``````