the code has nothing like gravity as such the chances that it will remain on ground with moving it goes towards 0 normally.
you will have to add some code to “press it against the ground” technically, be it through adding some term in the Translate or through using the found raycast hit point to reposition it before moving and alike
Don’t think gravity needs to be implemented here. Looks like basic surface following code. If the object remains parallel to the surface as it moves, the distance will remain constant.
If you want to do something like dreamora is suggesting, however, just use the surface normal as a guide. Get the difference between the distance from the surface the object is and the constant distance you want it to remain at (again, this is going with the assumption that you want it at a fixed distance…which I don’t think you do). Then you just translate the object in the positive or negative direction along the surface normal vector to correct.
My initial suggestion earlier wasn’t really a shot in the dark. They way you have it written, it moves first, then adjusts its rotation so the Y-axis is aligned with the surface normal. Problem I see with it as you wrote it, however, is that, because it moves first, it is not aligning itself with the surface normal where it is. It is aligning with the normal it was at prior to the translation. By first rotating the y-axis to align with the surface normal, you are ensuring that, when you translate it, it will be moving parallel to the surface.
@Maker16 yeah switching it did help slow the change but not completely.
@dreamora i am going to learn what you suggested, but i did manage to get it work with the simple change below. It probably isnt the good way but it does work.
var direction = transform.TransformDirection(Vector3.down);
var direction = transform.TransformDirection(Vector3(0, -0.8, .2));