- Home /
Question by
toishaanpatel · Jul 16, 2020 at 02:32 AM ·
raycastgrounddistance check
How do I make an object follow a player while staying above the ground x units?
I want to have the object follow the player, which I have already done, however, I am puzzled on how I can keep it, let say, 5 units above the ground at all times. I figure there needs to be some raycasting, but if someone can help me out, that would be great.
Comment
Best Answer
Answer by tuinal · Jul 16, 2020 at 03:36 AM
public LayerMask layerMask;
...
RaycastHit hit;
if(Physics.Raycast(transform.position, Vector3.up*-1f, out hit, Mathf.Infinity, layerMask)){
transform.position = new Vector3(transform.position.x, hit.point.y+5f, transform.position.z);
}
You need to put the object in a different layer to the ground, and set up the layermask in the inspector to only hit the ground layer (otherwise it will hit itself).
Thanks, this works great! I just used lerp afterwards to make it look nice, but this vector3 you created was all I needed. Thanks!