- Home /
How To Move Object To Terrain Slope in C# With Raycast?
I am trying to get a object to the same x and z as the terrain below it. My method right now is to get Raycast to get the normal and then trying to mess with transform.eulerAngles until they are the same. I fear this might be a little over my head though as I cannot figure this out for the life of me and I have been trying for several hours.
using UnityEngine; using System.Collections;
public class example : MonoBehaviour { public Vector3 hitr; public Vector3 hitrn;
void Update() {
RaycastHit hit;
Physics.Raycast(transform.position, Vector3.down, out hit);
if (Physics.Raycast(transform.position, Vector3.down, 2)){
hitr = hit.normal;
hitrn = hitr - transform.eulerAngles;
transform.Rotate(hitrn.x, 0, hitrn.z);
}
}
}
Answer by whydoidoit · Jun 03, 2012 at 10:22 AM
I see that you have two choices:
Presuming the normal coming from the raycast hit is what you need (it looks right when you use it):
transform.up = hit.normal;
If that doesn't do it, it might be better to sample a couple of points around the base of your model and then work out the slope angle from that
That does exactly what I wanted to do it. Can't believe I missed something so simple! Thank you very very much!
You are more than welcome! Please mark the question as answered.
And hey - I spent hours the other day before I remembered I could do that...
Answer by Tasarran · Jun 03, 2012 at 03:00 AM
Look in the docs at this component of the hit...
http://unity3d.com/support/documentation/ScriptReference/RaycastHit-barycentricCoordinate.html
That script there draws a Debug Line in the editor window, but you can modify it to do what you want.
I'm not trying to move along the X/Z world grid. I am trying to change my object's rotation to the same as the terrain below it.
Can you explain the effect you want? Are you looking to rotate the object to fit the slope of the terrain?
Yes! Generic as it is, it is for a basic tank character. It seems and feels like there is some variable or function I am missing to make this work.
Ok so then you are trying to rotate the green axis of your model to the normal you get from the terrain, I get it. These calculations are always a nightmare :)
Sorry to resurrect an old thread. I'm trying to do the same thing but for building instantiation. I want the player to be able to build on slight slopes. At the moment part of the building cuts through the terrain. If anyone can help out, let me know and I'll post my code.