0
\$\begingroup\$

There is a part in my script where I need to make a raycast check from my gun's muzzle to the enemy. This enemy could be anywhere around player.

I found my ray is not connecting to the target position!

public Transform target, Bullet_position;

void Update {

  if (target != null)
  {
      RaycastHit hit;
      if (Physics.Raycast(Bullet_position.position, target.position, out hit, 500)            
      {
          Debug.DrawRay(Bullet_position.position, target.position, Color.blue, 500);

          if (hit.collider.tag == "enemy")
          {
              print(" In range and I can see you! ");
          }
          else
          {
              print(" None! ");
          }
       }
    }           
} // end update.
\$\endgroup\$
3
  • 2
    \$\begingroup\$ You know the second argument is a direction, not a position, right? Did you mean to use a linecast? \$\endgroup\$
    – DMGregory
    Dec 30 '18 at 22:20
  • \$\begingroup\$ Yes, linecast is what I need for this script. Thank you DMG. \$\endgroup\$
    – Omer
    Dec 31 '18 at 7:28
  • \$\begingroup\$ Note also that you should use the CompareTag() method instead of .tag == \$\endgroup\$
    – DMGregory
    Dec 31 '18 at 15:42
1
\$\begingroup\$

The second argument in both of these methods is the direction you want the ray to travel, not the position you want it to reach. So when written like this...

if (Physics.Raycast(Bullet_position.position, target.position, out hit, 500))

Debug.DrawRay(Bullet_position.position, target.position, Color.blue, 500);

...you're asking for a ray along the line from:
Bullet_position.position
to:
Bullet_position.position + target.position

If you prefer to specify two points, instead of a point and a direction, you can instead use the LineCast / DrawLine methods.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .