- Home /
How to detect that a collider has moved out of the raycast instantly?
What I want to do is very simple: I constantly cast a ray in front of my character so when it detect something that can be interacted with (like a door), a little hint is rendered thanks to a canvas in the UI of the player.
My code works for stationary objects. But, if the raycast hits a door, and this door is opened, the hint doesn't disappear and still consider that the door -- which is now rotated and, in fact, not anymore at the range of the ray -- that the door is still in range.
It seems that the raycast doesn't update when something is moved. How can I make a hint appear when the player is in range to an interractable object?
Here's my actual code: (door = anything interractable)
using UnityEngine;
public class InteractScript : MonoBehaviour {
public float interactDistance = 3f;
public Canvas rend;
void Start()
{
var Hint2= GameObject.Find("Hint");
rend = Hint2.GetComponent<Canvas>();
rend.enabled = false;
}
void Update()
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, interactDistance))
{
if (hit.collider.CompareTag("Door"))
{
rend.enabled = true;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
hit.collider.transform.parent.GetComponent<DoorScript>().ChangeDoorState();
}
}
else
{
rend.enabled = false;
}
}
}
}
Answer by GamitusLabs · Oct 23, 2018 at 03:41 PM
So here's what you're doing:
If there is a hit within interact distance
{
If it is a door -> render hint
Otherwise -> stop rendering hint
}
Your statement to stop rendering the hint is only ever set if the object is hit, making it within the interact distance, it needs to be outside the interact distance... it's an easily overlooked logic bug.
Perhaps add something to the door that:
while hint active -> check distance to the player
when distance to player > interact distance
disable hint.
That was it. Thank you. For those interested, I just moved rend.enabled = false so it is not conditionnal anymore.
using UnityEngine;
public class InteractScript : $$anonymous$$onoBehaviour {
public float interactDistance = 3f;
public Canvas rend;
void Start()
{
var Hint2 = GameObject.Find("Hint");
rend = Hint2.GetComponent<Canvas>();
rend.enabled = false;
}
void Update()
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
rend.enabled = false;
if (Physics.Raycast(ray, out hit, interactDistance))
{
if (hit.collider.CompareTag("Door"))
{
rend.enabled = true;
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.$$anonymous$$ouse0))
{
hit.collider.transform.parent.GetComponent<DoorScript>().ChangeDoorState();
}
}
}
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Read txt file into a game 1 Answer
Instantiate 1 object after 2 objects collide. ( C# ) 1 Answer
Dying Script error 2 Answers