I am just trying to get my head around Raycasts and I’m struggling a bit. Basically, I am creating a town planning system, where I can place a building at the exactly ground level, not just at 0 on Y in the global axis.
I am using a game object as my general reference point (which my raycast script is attached to) and is the centrepoint for scanning around the map and controlled using the directional buttons. I have a variable hitDistance.distance that returns the distance to the ground (charmingly called distanceToGround), which varies over the map.
I just need to tell my “newBuilding” game object to sit constantly at 0.0 on the raycast y axis, so the building is, in effect at ground level as you scan over the map. As you hover around the map, the building would constantly be sitting on the ground, and not sinking at all.
I am prob missing something obvious, but I would really appreciate your help. Thanks![/list]
Keep an empty game object at a constant Y value (high enough to always be above the terrain), say Y = 1000 - move it across X and Z as you need. Let’s call this object “Ref”.
Raytrace straight down (-Vector3.up) from that object and measure the distance.
Then all you need to do is set the position of your building to:
Zambezi - I should have explained clearer, I am not using the Unity Terrain editor, its actually an FBX model which I have imported (its a town planner, so it has to be geographically correct)
.Tom. - Thats the kind of lines I was thinking, but its giving some fairly wierd results. it seems to be constantly flickering between two different positions, I assume between the CurrentPosition on the y axis and the CurrentPosition.position.y - distanceToGround.
The variable CurrentPosition represents the ref you mentioned. x and z axis works fine, but y is troublesome! DTMMask is looking at just the ground level model, and nothing else. newBuildingPos is the position of the new building in the environment.
Anyway I can eliminate this? I have attached a screenshot (green bar represents CurrentPosition.
function Update (){
var hitDistance : RaycastHit;
var DTMMask = 1 << 8;
if (Physics.Raycast (transform.position, -Vector3.up, hitDistance, 500.0, DTMMask)) {
var distanceToGround = hitDistance.distance;
}
newBuildingPos.transform.position = Vector3(CurrentPosition.position.x, CurrentPosition.position.y - distanceToGround, CurrentPosition.position.z);
}
Problem solved. I stupidly thought I could reference the Raycast I was measuring from! Attached to the controller and now works like a dream. Cheers for the help!