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?