Home > Software design >  How to show text using Raycast?
How to show text using Raycast?

Time:05-22

Basically what I'm trying to do here is to show a text when the player goes near the door saying "door is locked!", I want the text to show only when the player is in front of the door and gone when he is not looking at the door or when he goes further from the door. I tried the following code:

[SerializeField] private float maxDistance = 2f;
 void Update()
    {
        raycastPos = mainCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 0));
        RaycastHit hit;
        if (Physics.SphereCast(raycastPos, sphereCastRadius, mainCamera.transform.forward, out hit, maxDistance, 1 << interactableLayerIndex))
        {
            lookObject = hit.collider.transform.gameObject;
            if (hit.collider.gameObject.tag == "Door")
            {
                textUI.SetActive(true);
                centerUI.SetActive(false);
            }
            else
            {
                textUI.SetActive(false);
                centerUI.SetActive(true);
        }
        }
        else
        {
            lookObject=null;
        }

but the text never disappears. How can I fix it?

CodePudding user response:

Use a 3D-Collider Trigger instead

It is much efficient more than making ray-cast every single frame.

// This should be attached to your door
// with a trigger-collider
public class DoorDetector : MonoBehaviour {

    // Player needs a collider and any physics-body too.

    private void OnTriggerEnter(Collider other) {
        if (other.CompareTag("playerTag")){
            // Show the text, or something
        }
    }

    private void OnTriggerExit(Collider other) {
        if (other.CompareTag("playerTag")){
            // Hide the text, or something
        }
    }
}

This is the recommended way whenever you need to do something on detection, as making ray-casts per-frame can get expensive.


If you are looking to fix your issue, my guess is that you have forgotten to disable your UI once your Ray-cast out was of reach (or hit nothing).

[SerializeField] 
private float maxDistance = 2f;

void Update()
{
    raycastPos = mainCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 0));
    RaycastHit hit;
    if (Physics.SphereCast(raycastPos, sphereCastRadius, mainCamera.transform.forward, out hit, maxDistance, 1 << interactableLayerIndex)){
        lookObject = hit.collider.transform.gameObject;
        if (hit.collider.gameObject.tag == "Door") {
            textUI.SetActive(true);
            centerUI.SetActive(false);
        } else {
            textUI.SetActive(false);
            centerUI.SetActive(true);
        }
    } else {
        lookObject=null;
        // You probably forgot to decative the UI here, once the raycast was out-of-range
        textUI.SetActive(false);
        centerUI.SetActive(false);
    }
    // ...
  • Related