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);
– ArachnidAnimal