Raycasting doesn't seem to "hit" a Character Controller? [image]

I have code to check to see if an enemy can “see” the player. Unfortunately it seems that the Raycast isn’t hitting the player, who has a Character Controller attached.

I’ve googled, but none of the other answers seem to answer this. Any idea why Raycast wouldn’t hit the player?

[the yellow line is the Line drawn before the raycast, the cyan line is the line drawn between the enemy and the “hit” object. If the palyer was being hit, you’d see it in the consol and a lot of cyan lines, equal to the yellow lines.]

function OnTriggerStay (other : Collider)
{
	if (other.gameObject.tag == "Player")
	{
		var rayDirection = other.gameObject.transform.position - transform.position;
		rayDirection.y += 1;
		var currentPosition = transform.position;
		currentPosition.y += 1;
		var hit : RaycastHit;
		Debug.DrawLine (currentPosition, other.gameObject.transform.position, Color.yellow, 3);
		if(Physics.Raycast(currentPosition, rayDirection, hit, viewDistance)) 
		{
			Debug.DrawLine (currentPosition, hit.collider.gameObject.transform.position, Color.cyan, 3);
			print ("Hit: " + hit.collider.gameObject.transform.name);
			if(hit.collider.gameObject.tag == "Player")
			{
				print("Player found");
			}
		}
		
	}
}

Raycasting is tricky, and you should have a feel for Vector3 math and offsets vs positions. For example, adding +1 to rayDirection.y changes the angle by a semi-random amount (which is usually not what you want.)

I’d say rewrite lines 5-8, by figuring out where you want to shoot from, and where you want to shoot to. Then the last line computes the ray using computedTarget-ComputedStart.

Also, Debug.DrawRay doesn’t use the same math as Raycast. Close, but not the same. So you can have where drawRay seems to hit/miss, but the raycast is different.

Dude this is at least the 2nd time today you’ve posted the same question, thought I saw a third. Please don’t repeat. Again, I will ask you what is that calculation for raydirection doing? Why do you think that would point to your object? This is copy and pasted straight from the docs.

public class example : MonoBehaviour {
    void Update() {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        if (Physics.Raycast(transform.position, fwd, 10)){
            print("There is something in front of the object!");
        }
    }
}