Raycast Collision Not Working When Adding To The Y-Value Of transform.forward

Hello!

I’m having some trouble with a raycast.

I want it to print “hit” when the raycast collides with the enemy.

I’ve used this code and it works fine:

   var hit : RaycastHit;    
   Debug.DrawRay(transform.position, transform.forward * 20, Color.green);
 
   if(Physics.Raycast(transform.position, Vector3(transform.forward.x, transform.forward.y, transform.forward.z), hit, 20)){
      if(hit.collider.gameObject.name == "Enemy"){
           Debug.Log("Enemy Hit");
      }
   }

The only problem is that the Y-Value isn’t high enough, so I added 4 to the Y-Value as shown here:

   var hit : RaycastHit;    
   Debug.DrawRay(transform.position, transform.forward * 20, Color.green);
 
   if(Physics.Raycast(transform.position, Vector3(transform.forward.x, (transform.forward.y + 4), transform.forward.z), hit, 20)){
      //Debug.Log("Hit");    
      if(hit.collider.gameObject.name == "Enemy"){
           Debug.Log("Enemy Hit");
      }
   }

The raycast looked perfectly fine, but now it will not alert me when the raycast collides with the enemy.

Any help?

EDIT: I also found that if I replace:

Vector3(transform.forward.x, transform.forward.y, transform.forward.z)

With this:

Vector3(0.25f, 0.0f, 0.98f)

It still will not work.

You have added an amount to the direction of the ray, not its origin, so the ray starts at the same place but is angled upwards. If you intend to raise the start position of the ray, but otherwise leave it unchanged, then modify the first parameter to Physics.Raycast.

For consistency, you should also try and keep your debug code in sync with your raycast as otherwise you will have a hard time figuring out what is broken. Try something like this:

   var hit : RaycastHit;    
   var elevation : float = 4f;
   var range : float = 20f;
   var origin : Vector3 = transform.position + transform.up * elevation;

   Debug.DrawRay(origin, transform.forward * range, Color.green);

   if(Physics.Raycast(origin, transform.forward, hit, range)){    
      if(hit.collider.gameObject.name == "Enemy"){
           Debug.Log("Enemy Hit");
      }
   }