RaycastHit.point always origin
I was attempting to spawn prefabs on a mask mesh which is over a sphere. The mask mesh is simply a sphere with the top and bottom sliced off, the idea being the prefabs will be buildings on a planet and I don't want them to show up in the ocean or weird places like the polls.
Here's the code I'm using:
public class SpawnIndustries : MonoBehaviour {
public GameObject prefab;
// Use this for initialization
void Start () {
spawn(prefab);
}
public RaycastHit GetPointOnMesh()
{
float length = 100.0f;
Vector3 direction = Random.onUnitSphere; Debug.Log(direction);
RaycastHit hit;
Physics.Raycast(transform.position, direction, out hit, length, 1<<8);
return hit;
}
public void spawn(GameObject p)
{
RaycastHit randomPoint = GetPointOnMesh();
Instantiate(p, randomPoint.point, Quaternion.identity);
Debug.Log(randomPoint.point);
}
}
However when the code runs it will always spawn my prefab at the origin. I'm not sure what could be causing this. The mask is on the correct layer (8) and the sphere itself has no collider which could be interfering with the script. Not sure what I could be doing wrong.
Answer by Omega3939 · Mar 28, 2017 at 12:52 AM
I figured it out! The problem was Rays that originate inside a collider wont hit anything. The solution was to make the ray originate OUTSIDE the sphere and then shoot it in the opposite direction toward the center.
public void spawn(GameObject p)
{
float length = 100.0f;
Vector3 direction = Random.onUnitSphere; Debug.Log(direction);
RaycastHit hit;
if (Physics.Raycast(transform.position + direction*length, -direction, out hit, length, 1 << 8)) //starts outside and goes in opposite direction
{
Instantiate(p, hit.point, Quaternion.identity);
Debug.Log(hit.point);
}
}
Leaving this here if someone comes across this. Sorry for wasting disk space.