- Home /
Raycast Will Only Hit Target If Jumping Over Object Firing Raycast
I always have raycast issues. They never work for me and people can never find out why. So, I'm really trying to fix it here. I have a youtube link to a video of what's happening and I have my entire script that the raycast is in. Everything that I don't want to get in the way of the raycast is set to the IgnoreRaycast layer and in the video, you can clearly see that the Debug.DrawLine() is working fine. I'm really not sure what's wrong with it, please help.
private GameObject player;
[SerializeField] private float lookDistance = 10f;
private void Awake()
{
player = GameObject.FindGameObjectWithTag("Player");
}
private void OnTriggerStay(Collider other)
{
if(other.gameObject == player)
{
RaycastHit hit;
Debug.DrawLine(transform.position, other.transform.position, Color.green);
if (Physics.Raycast(transform.position, other.transform.position, out hit))
{
Debug.Log("Hit");
}
}
}
What exactly is the geometry of your portal? Have you tried with a simple cube ins$$anonymous$$d? It might be an issue with the geometry and not with the raycast itself.
Answer by SamuelRoos · Jun 07, 2020 at 02:59 AM
The Debug.DrawLine() function takes in two positions: a start pos parameter as well as an end pos parameter. However, the Raycast takes in a start position but instead of an ending position, it requires a direction. What you are doing here is setting the direction of the raycast as the position of the other object, which leads to incorrect results and the DrawLine still showing it as "correct". This is how you'd calculate the direction in your case:
private void OnTriggerStay(Collider other)
{
if(other.gameObject == player)
{
RaycastHit hit;
Debug.DrawLine(transform.position, other.transform.position, Color.green);
//direction in this case = target position - raycast start position
Vector3 rayDirection = other.transform.position - transform.position;
if (Physics.Raycast(transform.position, rayDirection, out hit))
{
Debug.Log("Hit");
}
}
}
I completely forgot that I tried using the position ins$$anonymous$$d of direction. I was testing to see if it worked and since it gave no error message I assumed it was fine and forgot about it. Thanks.
Your answer
Follow this Question
Related Questions
2 raycasts on the fpwalker/camera 1 Answer
How to move while jumping? 1 Answer
Cube clips and falls through wall when held 0 Answers
Better 2D Sprite Jump in 3D Plane 1 Answer
Problem with jumping 2 Answers