- Home /
Raycast hitdetection not working correctly
Hey guys, I am currently trying to use a Raycast in Order to trigger an interaction with an Object in my Gameworld, in this Case an Item. For this I am using this Skript:
public class PlayerController : MonoBehaviour
{
private Vector3 fwd;
private RaycastHit hit;
public float range;
public Camera mainCamera;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown("e"))
{
fwd = mainCamera.transform.forward;
if (Physics.Raycast(mainCamera.transform.position, fwd, out hit, range))
{
if (hit.collider.gameObject.tag == "Interactable")
{
Interactable i = hit.collider.gameObject.GetComponent<Interactable>();
i.Interact();
}
}
}
}
}
For now, the only thing that should happen if the Raycast hits an Item is to show the message "Interacted" in the Console.
Now if i stand in front of my Object nothing will happen:
But if I use my crouch function, which will move my Player down a bit, it works just fine:
I added the Skript to my Player Gameobject and connected the Main Camera, I also tried to higher the radius but it didn't help.
What am I doing wrong?
Answer by jackmw94 · Nov 08, 2020 at 10:42 PM
It's hard to debug these things without seeing your setup but my best advice is to use gizmos to show the exact ray you're raycasting. Have ray as a private member then use:
ray = new Ray(mainCamera.transform.position, fwd);
if (Physics.Raycast(ray, out hit, range))
{
...
and
private void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawRay(ray);
}
Then the green line you see in the Scene View will be the ray you're casting along, which should tell you why you're hitting / not hitting what you're expecting.
Given that you are getting some hits I'm assuming that you have colliders on all things you are planning on hitting but thought it worth mentioning incase you're hitting something else, getting false positives.
Answer by enchantedf0rest1 · Nov 08, 2020 at 11:36 PM
Maybe you need to call the Raycast hit in void update so instead try this, also you should get hit.transform.gameObject
void Update()
{
if (Input.GetKeyDown("e"))
{
fwd = mainCamera.transform.forward;
RaycastHit hit;
if (Physics.Raycast(mainCamera.transform.position, fwd, out hit, range))
{
if (hit.transform.gameObject.tag == "Interactable")
{
Interactable i = hit.transform.gameObject.GetComponent<Interactable>();
i.Interact();
}
}
}
}
}
How does this make any difference to the original script?
Your answer
Follow this Question
Related Questions
Raycast only works while moving 2 Answers
Another Raycast Issue. 0 Answers
Can't find a clone object with RayCast? [Solved] 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers