- Home /
Checking if ground is 'level'
I am attempting to create RTS style "structure" placement on a surface and I need to check if the ground area below the structure is level. In order to do this, I am casting rays from 9 points around the structures 'bounds' and averaging the hit normals to ensure the ground can be considered level. In order to do that, I am having to create an array of 9 points like so:
Vector3 lpos = new Vector3(_tr.position.x - _groundMarker.renderer.bounds.extents.x, _tr.position.y, _tr.position.z);
Vector3 rpos = new Vector3(_tr.position.x + _groundMarker.renderer.bounds.extents.x, _tr.position.y, _tr.position.z);
Vector3 tlpos = new Vector3(_tr.position.x - _groundMarker.renderer.bounds.extents.x, _tr.position.y, _tr.position.z - _groundMarker.renderer.bounds.extents.z);
Vector3 trpos = new Vector3(_tr.position.x + _groundMarker.renderer.bounds.extents.x, _tr.position.y, _tr.position.z + _groundMarker.renderer.bounds.extents.z);
Vector3 blpos = new Vector3(_tr.position.x - _groundMarker.renderer.bounds.extents.x, _tr.position.y, _tr.position.z + _groundMarker.renderer.bounds.extents.z);
Vector3 brpos = new Vector3(_tr.position.x + _groundMarker.renderer.bounds.extents.x, _tr.position.y, _tr.position.z - _groundMarker.renderer.bounds.extents.z);
Vector3 tmpos = new Vector3(_groundMarker.renderer.bounds.center.x, _tr.position.y, _tr.position.z + _groundMarker.renderer.bounds.extents.z);
Vector3 bmpos = new Vector3(_groundMarker.renderer.bounds.center.x, _tr.position.y, _tr.position.z - _groundMarker.renderer.bounds.extents.z);
Vector3 cpos = _groundMarker.renderer.bounds.center;
I am having to update these vectors every time the ground marker changes scale (depending on the size of the structure) and it just strikes me as kind of messy. Is there a better way to do this without having to cast 9 individual rays? It's be nice if I could simplify this code right down. Any suggestions?
Answer by Owen-Reynolds · Jan 09, 2012 at 04:34 AM
Raycasting is when you aren't sure what might be down there -- maybe the ground, or a rock collider, or a platform... . If you know you want to check the ground, can just look it up:
float HT = Terrain.activeTerrain.SampleHeight( lpos );
// lpos.y is ignored, but has to be set
If you want to pretty up the code, could use loops to find the 9 points. Won't be any less work for the computer:
Vector3[] P = new Vector3[9];
for(int xp=-1; xp<=1; xp++) // xp and zp go through every combination
for(int zp=-1; zp<=1; zp++) // of (-1,0) (1,1) ...
P[xp*3+zp] = new Vector3( xp*extents.x, 0, zp*extents.z);