- Home /
Object over terrain
How I can keep an object at a height above the ground, using raycast?
something like that:
Answer by Positive7 · Aug 26, 2015 at 10:09 PM
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);
}
}
Answer by Covenant · Aug 27, 2015 at 12:23 PM
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
// Ideally you'd set terrainMask in your Start or Awake function,
// no need to create this everytime this function is called
LayerMask terrainMask = 1 << LayerMask.NameToLayer ("Terrain");
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;
}
Your answer
Follow this Question
Related Questions
Script on Prefab is not changeable without changing all other instaniated objects 1 Answer
Can we refer to two rigidbodies2d in a single script? 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can i avoid mouse double click on second time to make my player idle ? 1 Answer