Object over terrain

How I can keep an object at a height above the ground, using raycast?

something like that:

Is this 2d or 3d game?

If it’s 3d, you could cast a Ray with an origin a little above your object with Vector3.down as the direction.
Then you’d call Physics.Raycast using a layermask so it’d only try to hit the terrain. Make sure you set your terrain objects to use a new layer called “Terrain” (or whatever you want to name it, just make sure the layermask has same name). If it hits, look at hit.point to get the position in the world. Then you just have to offset it so it’s however higher you want. Like so:

``````private Vector3 FloatObjectAboveTerrain(Vector3 objectPos)
{
// objectPos is position of your object

// no need to create this everytime this function is called

Vector3 rayOrigin = objectPos;

// Raise ray origin point up some so it'll float
// above the object and point downwards
rayOrigin.y += 5.0f;

Ray ray = new Ray(rayOrigin, Vector3.down);
float distanceToCheck = 100f;
RaycastHit hit;

if (Physics.Raycast (ray, out hit, distanceToCheck, terrainMask))
{
// The ray hit an object with layer "Terrain"

// hit.point is the point where the ray hit
// The y value is how high the terrain is
Vector3 floatingPos = hit.point;

// Here is where you add however much height
// so your object will float above the terrain
floatingPos.y += 0.2f;

return floatingPos;
}

// No terrain was hit by the ray, return object's original position
return objectPos;
}
``````

Something like this :

``````using UnityEngine;

public class floatObj : MonoBehaviour {

public GameObject objToFloat;
public float floatValue = 0.7f;                //0.2m + obj height /2
//Optional solution
//public GameObject terrain;

void Update () {
var objPos = objToFloat.transform.position;

//For the Optional solution Delete from Here
RaycastHit hit;
if (Physics.Raycast (objPos, Vector3.down, out hit)) {
objToFloat.transform.Translate (0, (floatValue - hit.distance), 0);
}
//To here. Then Uncomment below.

//OR Optional
//var terPos = terrain.transform.position;
//objToFloat.transform.position = new Vector3 (objPos.x,terPos.y + floatValue,objPos.z);
}
}
``````