Raycast Help

ok I have this script, I’m trying to create ai for the enemy. and I cant seem to figure out why the if statement isn’t returning true… any ideas. It draws the line from the enemy to the player. the hit just doesn’t return true

   Vector3 fwd = player.transform.position - transform.TransformDirection(transform.forward);
				Debug.DrawLine(transform.position, fwd);
		if(Physics.Raycast(transform.position, fwd, maxDistance) (collider.gameObject.tag == "Player")){
			
			Debug.Log("Can see player");
		}

I know its something simple and obvious…
I’m just missing it

I did something similar today went like this:

Transform targetTransform = target.transform;
Transform myTransform = transform;
Vector3 rayDirection = targetTransform.position - myTransform.position;
float dist = Vector3.Distance(myTransform.position, targetTransform.position);
Raycast hit; 

if(Physics.Raycast(myTransform.position, rayDirection, out hit, dist){
      if(hit.collider.gameObject.tag == "Enemy"){
             //do stuff
      }

}

Did it work for you?

yeah, i think all you were missing was that “out hit”

Yes, you cant use collider if you don’t have a Raycast hit, just using collider makes it use the GameObjects collider, has nothing to do with the raycast. Need to use hit.collider.

Actually the main problem is that your math is wrong, and you should be using DrawRay rather than DrawLine. But it’s a lot simpler if you use Linecast rather than Raycast for this anyway, then you don’t need any math.

–Eric

I’ve defined the raycasthit and used out hit, and it didn’t work. I’ll look into the solutions provided here and see what happens…