I’m creating a spawn script using a collider sphere, but I’m having problems when instantiating it randomly because of a irregular ground, how can I rotate my gameobject (that uses rigid body or character controller) before instantiating it so it will not “get inside” my terrain?
One way is to raycast. I assume that you generate a Vector3 position on the terrain. I don’t know how your project is setup. If you don’t have object on your terrain that you have to contend with, then you could use the more efficient Collider.Raycast() rather than Physics.Raycast(). You could do something like:
var hit : Raycast hit;
var ray : Ray = new Ray(position + Vector3.up * 10.0, Vector3.down);
if (terrainCollider.Raycast(ray, hit)) {
var go = Instantiate(goPrefab) as GameObject;
go.transform.position = position + Vector3.up * halfCharacterHeight;
go.transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
}
else {
Debug.Log("Error: Position is not over the terrain");
}