Why can't raycast detect the objects?

I’m working on a feature that uses raycasts for interaction. But I met a problem.(btw: It’s a 3D game)

The Player as a whole is a first-person controller based on the CharacterController. It has a camera at its head that emits raycast, which are used for interaction.(The script is below this paragraph).

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Interactions : MonoBehaviour
{
    [SerializeField] private float raycastLength = 7f;

    public LayerMask Player;

    public GameObject UseIcon;
    public GameObject ScreenDot;

    private void Start()
    {
        
    }

    private void FixedUpdate()
    {
        InteractionRay();
    }

    private void InteractionRay()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, raycastLength))
        {   
            if (hit.collider.gameObject.tag == "shotgun")
            {
                UseIcon.SetActive(true);
                ScreenDot.SetActive(false);
            }
            else
            {
                UseIcon.SetActive(false);
                ScreenDot.SetActive(true);
            }
        }
        else
        {
            UseIcon.SetActive(false);
            ScreenDot.SetActive(true);
        }
        Debug.DrawRay(transform.position, transform.forward * raycastLength, Color.yellow);
    }
}

At first, raycast can detecting objects labeled “shotgun” well at the right distance, but when it is close and the camera’s angle of view is pulled down too much, the raycast will hit the Player inexplicably, causing the objects labeled “shotgun” to be undetectable by the raycast directly below the Player. How to solve this problem?

As was mentioned in below answer to use a layer mask. It looks like you already have a LayerMask defined in the code, you just didn't pass it in to the Raycast function. Raycast(origin, direction, out RaycastHit hitInfo, maxDistance, layerMask);

1 Answer

1

Hi,

I think that hitting your player with a raycast starting from the camera can easily be done if you’re not limiting the camera rotation, so you have to deal with it.
And to deal with this, I suggest you to use a layer mask : Unity - Scripting API: Physics.Raycast (unity3d.com)
Set your layer mask to ignore the player layer.


A little bit off topic but as I see it in your code, I suggest you to put your raycast method inside the Update() function, as you want it to be done per frame and not at a non frame-dependent timing.

Ideally, the camera SHOULD be inside the player collider to prevent it from clipping through items.