- Home /
Ray does not hit TreeInstance
Hi Guys,
I can't seem to solve a quite simple problem, and it is driving me insane. I can't raycast the tree instances on my terrain.
Here are a few screenshots: I draw the ray, in red if it hits something, in blue if it does not hit anything.
As you can see, the rays hit the terrain, but do not hit the tree.
Here is the prefab I am using, it has a capsule collider.
Code wise here is what is going on:
Raycasting:
RaycastHit hit;
Ray ray = new Ray (mainCamera.transform.position,
mainCamera.transform.TransformDirection (Vector3.forward));
if (Physics.Raycast (ray, out hit, 100f)) {
Debug.DrawRay (ray.origin, ray.direction * hit.distance, Color.red, 10f);
} else {
Debug.DrawRay (ray.origin, ray.direction * 200f, Color.blue, 10f);
}
Creating the tree instance
TreeInstance treeInst = new TreeInstance();
treeInst.prototypeIndex = 0; // that gets me my treeprefab
treeInst.color = Color.yellow;
treeInst.lightmapColor = Color.white;
treeInst.widthScale = 1f;
treeInst.heightScale = 1f;
treeInst.position = position;
terrain.AddTreeInstance(treeInst);
Can't see what is going wrong, I read about all the posts on the subject. any input is appreciated.
If I instanciate a tree from this prefab as a GameObject, then the raycast hits it, the problem is only when the tree is a terrain TreeInstance.
Cheers!
Answer by Bentaye · Apr 26, 2015 at 08:31 PM
Ok, I got it sorted, it seems that the TerrainCollider is generated when the terrain is generated. As I add the trees afterwards, it needs some kind of refresh to include the TreeInstances. I did it this way, and it takes the trees into account afterwards:
terrain.GetComponent<TerrainCollider>().enabled = false;
terrain.GetComponent<TerrainCollider>().enabled = true;
I also tried
terrain.Flush ();
but it did not work.
Your answer
Follow this Question
Related Questions
Getting treePrototype information from RayCasting collisions onto terrain? 2 Answers
Tree how to add a tag to it when it is apart of the terrain -1 Answers
How can I separate tree colliders from terrain colliders? 2 Answers
Making a particle effect parallel to the slope of a terrain 1 Answer
Placing tree objects with Terrain or Polybrush which one is useful ?? 0 Answers