- Home /
How to make object stay certain distance above ground (relative o ground normal)
I am making a game where an object must stay 8 units above the ground at all times. I can do this easily with flat ground since you just add 8 to the hit.point property of the raycast and assign it to the y component of the position of the object, however this does not work when the ground is upside down, vertical, diagonal, etc. I want it relative to the ground normal. So 8 units above (locally) an upside down ground would really be 8 units down in world axis. How would I achieve this? I know some raycasting needs to be done probably, however I am not sure how to approach this.
Answer by toishaanpatel · Nov 28, 2020 at 04:40 AM
Nevermind, I seemed to have figured out my problem. For anyone else that is interested, ere is what I got.
//shoot a raycast relatively downwards
if (Physics.Raycast(transform.position, -transform.up, out hit, Mathf.Infinity))
{
Vector3 pos = hit.point; //get the position where the ray hit the ground
//shoot a raycast up from that position towards the object
Ray upRay = new Ray(pos, transform.position - pos);
//get a point (vector3) in that ray 8 units from its origin
Vector3 upDist = upRay.GetPoint(8);
//smoothly interpolate its position
transform.position = Vector3.Lerp(transform.position, upDist, );
}
Your answer
Follow this Question
Related Questions
Getting a Vector2 position depending on the rotation of an object 0 Answers
NullReferenceException when using raycast 1 Answer
How can I Instantiate a prefab (projectile) consistently from the character? 0 Answers
Moving object with transform.position ignore other objects even if they collided 1 Answer
2D RPG boomerang instantiation help. 2 Answers