- Home /
Terrain height raycasting?
I'm quite new to javascript and c# and I don't really care in which the following code should be programmed.
I have a gameobject that follows my mouse, just floating in 3d space. I want to make it stick to the ground which is a terrain object. It has come to my understanding that the best way to do this is to raycast for the y on the terrain, but I have no clue how to get this done. Can anyone help me on this subject?
This is the code I have so far (Javascript):
var depth = 10.0;
function Update ()
{
var mousePos = Input.mousePosition;
var wantedPos = Camera.main.ScreenToWorldPoint (Vector3 (mousePos.x, (mousePos.y, depth));
transform.position = wantedPos;
}
I guess I have to change the mousePos.y to the variable in which I store the terrain height or something. Any ideas?
Answer by syclamoth · Jan 31, 2012 at 11:29 AM
What you should use is this:
RaycastHit hit;
if(Camera.main.ScreenPointToRay(Input.mousePosition, out hit))
{
transform.position = hit.point;
}
If your box has a collider, you may want to put it on a different layer, and include a layermask in the raycast so that it ignores the box.
Your answer
![](https://koobas.hobune.stream/wayback/20220613063600im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity 5 Terrain glitch 0 Answers
Get Height of Terrain in Script 1 Answer
How do I get the y coordinate of a terrain at any time? 1 Answer
Having some serious issues making height maps work. 1 Answer
Editing Terrain Topology at Runtime 0 Answers