# Keeping object a fixed distance from the ground, buggy behavior

I'm trying to make a script that will keep my object exactly 1 meter from the ground. So far I've got the following code : using UnityEngine; using System.Collections;

public class HoverScript : MonoBehaviour {

public Transform target;
public float hoverDistance;
void Start ()
{

}

void Update ()
{

}

void FixedUpdate ()
{
if (Physics.Raycast(transform.position, Vector3.down, hoverDistance))
{
RaycastHit hitInfo;
Physics.Raycast(transform.position, Vector3.down, out hitInfo, hoverDistance);
float correction = hoverDistance-hitInfo.distance;
//Debug.Log(correction);
//Debug.Log(target.position);
target.position = new Vector3(target.position.x, target.position.y+correction, target.position.z);
//Debug.Log(target.position);

}
}
}


Basically, if the raycast hits, then it finds the distance of the hit. If it's .9 and the hoverDistance is 1, it would push the object up by .1, and keep checking every update. It seems like it would work, but I get this result : http://www.gfycat.com/IllfatedMediocreAquaticleech

In case the link goes down, basically the object falls like normal because of gravity until the distance is reached, then it slows down dramatically and slowly sinks into the ground.

The objects are set up like this

gameObject(has hover script, rigidbody, the camera following script)
|
----> mesh(just a mesh, mesh renderer, and collider)


The target of the script is the parent gameObject.

Any ideas why this script isn't working?

• Looks like you're setting the position of the object, but not its velocity. That means it's continuing to accelerate downward under gravity. So its position pre-physics-step is correct, but then its (gradually increasing) vertical velocity displaces it from that point at the end of the physics step, before the next frame is rendered. Dampening, opposing, or zeroing the velocity may help. – DMGregory Feb 4 '15 at 17:27
• That's probably it, I didn't think about how velocity would be constantly increasing. I'll try resetting the y velocity when the ray hits when I'm at my computer next. – Marcus Buffett Feb 4 '15 at 17:33
• Generally, if an object has a Rigidbody, it's best to leave its Transform alone and only influence its movement through space via forces & velocities. That ensures everything reacts in reasonable ways during collisions and such, and makes teleportation/tunneling issues less common. – DMGregory Feb 4 '15 at 18:01

## 1 Answer

If you replace your transform.position = vector... with rigidbody.MovePosition( vector... ) this will give you better results. It will also interpolate (if you have interpolation on for your rigidbody) so it looks smooth between your FixedUpdate.

Here's the doc page: https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html