Help with Raycasting direction?

Rays will only detect an object from the origin to a fixed direction, So how can I do it so rays can detect an object from origin to any direction it is being pointed at?

For example, From the left side. Rays do not detect an object and is not shown in the debug either.Screenshot by Lightshot Screenshot by Lightshot

But from the front, it will detect the object. Screenshot by Lightshot Screenshot by Lightshot

Here is the code I currently have at the moment.

private void FixedUpdate()
{
Ray ray = new Ray(transform.position, Vector3.forward);
RaycastHit hit;

Physics.Linecast(transform.position, -transform.up * maxRayDistance, Color.red);

if (Physics.Raycast(ray, out hit, maxRayDistance))
{
Debug.DrawRay(transform.position, -transform.up * maxRayDistance, Color.red);

if (hit.transform.gameObject.tag == “Enemy”)
{

Debug.Log(“You hit a ray”);
rayHitInvis(hit.transform);

}

}

}

A couple of things confuse me about your code.

  • You’re calling Linecast, but not doing anything with the result.
  • When calling Raycast, if successful, you call DrawRay, but you draw a different ray than the one you were just raycasting for. (Your raycast was looking forward, but your DrawRay is drawing a ray downward?

The pictures you show trying to detect and object from the “left side” don’t show any object in the scene to detect. What object were you hoping to detect in the first two screenshots? Because there doesn’t seem to be anything there…

What kind of collider do you have on the object you’re hoping to hit?

As an aside, another approach you could take is to add an invisible cone (no mesh filter) to your object, and make it a trigger collider. Then detect collisions between that cone and your targets. I’m not sure whether that’s cheaper than doing several raycasts per frame, but it’s a potentially simpler implementation conceptually and in code.

-Dan

also this will set ray direction towards forward in world direction,

Ray ray = new Ray(transform.position, Vector3.forward);

maybe you want transform forward instead (or others like transform.up, right…)

Ray ray = new Ray(transform.position, transform.forward);
1 Like