- Home /
Raycast not Detecting Colliders
Raycast does not seem to be hitting colliders. My walls are in their own layer but putting them in the default layer did not change anything. The Debug.DrawRay() and Debug.Log(hi1.transform.name) are not returning anything but I'm sure the Shoot() method is being invoked because of my other Debug.Logs.
public class ShootP1 : MonoBehaviour { public GameObject Shooter;
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown("r"))
{
Shoot();
//Debug.Log("Pressed");
}
}
void Shoot()
{
RaycastHit hit1;
//Debug.Log("shot");
if (Physics.Raycast(Shooter.transform.position, Shooter.transform.forward, out hit1, 1000))
{
Debug.DrawRay(Shooter.transform.position, Shooter.transform.forward, Color.cyan);
Debug.Log(hit1.transform.name);
}
}
You might want to try that DrawRay() before the Raycast to see where your ray is actually being shot. I’d suggest you start there
EDIT: Put the DrawRay right in the update so you can see where it’s shooting off to at all times. Quite sure it’s missing your target
Answer by kylecat6330 · Feb 05, 2020 at 06:41 AM
It might be an issue with the Shooter.transform.forward being a local direction in which case just add a transform.TransformDirection into the ray cast.
Physics.Raycast(Shooter.transform.position, Shooter.transform.TransformDirection(Vector3.forward), out hit1, 1000)
That would be my best guess, but I am no expert. If that doesn't work you should put a Debug.DrawRay before the ray cast to make sure it is actually going where its is supposed to.
Debug.DrawRay(Shooter.transform.position, Shooter.transform.forward * 1000, Color.cyan);
Answer by kskjadav007 · Feb 05, 2020 at 09:48 AM
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("r"))
{
Shoot();
Debug.Log("Pressed");
}
}
void Shoot()
{
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(Shooter.transform.position, Shooter.transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity))
{
Debug.DrawRay(Shooter.transform.position, Shooter.transform.TransformDirection(Vector3.forward) * hit.distance, Color.green,10f);
Debug.Log("Did Hit");
Debug.Log(hit.transform.name);
}
else
{
Debug.DrawRay(Shooter.transform.position, Shooter.transform.TransformDirection(Vector3.forward) * 1000, Color.red,2f);
Debug.Log("Did not Hit");
}
}
this is working