Why is my Raycast returning nonsense? (Solved)

I’ve been trying to figure out this one error all damn night and I’m just flabbergasted about what it could be at this point.

I’m shooting a raycast from an enemy to the player to try and determine line of sight and it’s just flat out not working.

I told it to mask everything but the player and untagged items, then do an update whenever the ray hit the player. But it was only hitting the player randomly and not at all consistently.

        var layerMask1 = 1 << 0;
        var layerMask2 = 1 << 12;
        var myLayerMask = layerMask1 | layerMask2;
        RaycastHit hit;
        if(Physics.Raycast(transform.position + transform.up, player.transform.position, out hit, myLayerMask)){
            Debug.DrawLine(transform.position + transform.up, player.transform.position);
            if (hit.transform.tag == "Player"){
                Debug.Log("I see you.");
                Spotted();
                return;
            }

Getting desperate, I went ahead and tried this as a test every frame:

    void SearchTest()
    {
        Debug.Log("Searching!");
        Debug.DrawLine(transform.position, player.transform.position);
        RaycastHit hit;
        if (Physics.Raycast(transform.position, player.transform.position, out hit))
        {
            Debug.Log("I hit a " + hit.transform.tag);
            Debug.Log("I hit something!");
        }
    }

This is where it gets weird, the thing is hitting items that aren’t even close to where it should be aiming, such as health packs that are in the opposite direction as the player.

Oh, and needless to say I double checked all my tags and the debug.drawline shows exactly what I want the ray to do.

if (Physics.Raycast(transform.position, player.transform.position - transform.position, out hit))

The second variable isn’t the destiniation, it’s the direction.

2 Likes

Well that make sense.

I’ll just use a linecast then I guess.

Thanks @FlashMuller !