- Home /
How to place an object on terrain without turning it?
I'm not very good at coding, but is there a way to write a small script so that when I place an item, say a house on terrain, I wouldn't have to always adjust and keep estimating what angle it should be on the terrain when already placed, and it requires a huge amount of time spent. I want it to be automatically allign to the terrain! If you can help, I would appreciate it!
When you get a RaycastHit object, it includes the outward normal of that Raycast. You can use this to get started.
The end result looks something like this. (gif)
void Update ()
{
if ( Input.Get$$anonymous$$ouseButton (0) )
{
// First, check if the mouse was over an object.
RaycastHit mouseHit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if ( Physics.Raycast (ray, out mouseHit) )
{
// Visualize what's happening
Debug.DrawLine (Camera.main.transform.position, mouseHit.point, Color.red);
Debug.DrawRay (mouseHit.point, mouseHit.normal, Color.green);
// Check that this worked.
if ( Input.Get$$anonymous$$ouseButtonDown (1) )
{
GameObject newCube = GameObject.CreatePrimitive (PrimitiveType.Cube);
// Adjust the cube, note that we're assigning its Upward normal
// to be that of our normal vector.
//
newCube.transform.localScale = Vector3.one / 5f;
newCube.transform.position = mouseHit.point;
newCube.transform.up = mouseHit.normal;
}
}
}
}
I appreciate this, is there a way to impliment something like this into the editor?
Yes, with the adjustment of Camera.main
to Camera.current
.
Raycasting can happen in the editor as well, more in this post: http://answers.unity3d.com/questions/62655/raycasting-in-unity-editor.html
Interestingly, the post also mentions goofy behavior raycasting from Camera.current, so they recommended: https://docs.unity3d.com/ScriptReference/HandleUtility.GUIPointToWorldRay.html
You would then use those pieces within an editor script's OnSceneGUI() call: https://docs.unity3d.com/ScriptReference/Editor.OnSceneGUI.html