- Home /
Why is raycast not ALWAYS working?
I am raycatsing a plane (with collider) 10 times, but for a reason I cannot understand, only a few times a hit is registered and a sphere is generated on that position. I used a Debug.DrawRay to simulate the raycats to amke sure the ray is supposed to hit, but it does not. Is there anyone that can help me?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorldGenerator : MonoBehaviour
{
public int seed = 11;
public Material planeMaterial;
public Material sphereMaterial;
void Start()
{
Random.InitState(seed);
AddPlane();
AddSpheres(10);
}
private void AddSpheres(int maxSpheres)
{
for (int i = 0; i < maxSpheres; i++)
{
float posX = Random.Range(-14, 14);
float posZ = Random.Range(-14, 14);
Vector3 rayPos = new Vector3(posX, 50, posZ);
RaycastHit hit;
Debug.DrawRay(rayPos, Vector3.down * 100, Color.yellow, 1000);
if (Physics.Raycast(rayPos, Vector3.down, out hit, 100))
{
Debug.Log(i + ": " + hit.distance);
GameObject newSphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); //Instantiate(gameWorld.islandShapes[Random.Range(0, gameWorld.islandShapes.Length)]);
newSphere.name = "Sphere_" + i;
newSphere.transform.position = new Vector3(posX, 0, posZ);
newSphere.transform.localScale = new Vector3(5, 2, 5);
newSphere.transform.rotation = Quaternion.identity;
newSphere.GetComponent<MeshRenderer>().material = sphereMaterial;
}
}
}
private void AddPlane()
{
GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
plane.transform.localPosition = new Vector3(0, 0, 0);
plane.transform.localScale = new Vector3(3, 1, 3);
plane.GetComponent<MeshRenderer>().material = planeMaterial;
}
}
Answer by SellPet · Feb 13 at 03:49 PM
check if the ray is going where you want
onDrawGizmos(){
Gizmos.DrawRay(Paste same ray origin and direction);
}
you will see the ray in the viewport. if it does go where you want i would recommend changing collider to cube collider. and see if the problem goes
Answer by edwarddewolf · Feb 13 at 04:12 PM
I added a boxCollider to the plane, and now it works perfectly. Is there a reason why the default meshcollider on a plane would not notice all the raycast hits and a boxcolldier does?
Actually, as far as I understand with my limited knowledge, I found the real reason, I got it working with a default meshcollider now too.
The real issue is that I cam doing this from a start function, which has as a side effect that the physics engine might not have caught up with adding all the objects and colliders.
If I disable Physics.autoSimulation, and add Physics.Simulate(1); in between adding each gameobject , all raycasthits are behaving as expected and will collide with all previously placed objects
Do not forget to enable Physics.autoSimulation afterwards