- Home /
Raycast and drawray problems
Hello... Im making a FPS on C# and im having some problems with the Raycast.
Vector3 fwd = direction.transform.position;
RaycastHit hit;
if (Physics.Raycast(fwd, transform.forward, out hit)) ;
{
Debug.DrawRay(fwd, transform.forward, Color.red, 5F);
if (hit.transform.gameObject.tag == "Wall")
{
print("HITwall");
}
if (hit.transform.gameObject.tag == "Enemy")
{
//print("HITenemy");
GameObject.FindWithTag("Enemy").GetComponent<FSMSimples>().DmgOn = true;
}
The draw should begin at the direction position (the direction is an empty gameobject attached to the gun), but its starting far away from it.
The red line is the draw from the Debug.DrawRay. Can someone help?? I dont know what to do. Tnks!
Which object is 'direction'? Why don't you just use
Physics.Raycast(transform.position, transform.forward, out hit)
$$anonymous$$ake sure you aren't getting any of the parameters mixed up.
Answer by Owen-Reynolds · Nov 08, 2011 at 01:05 AM
There's a semi-colon after your if. That makes the lines after it not part of the IF, so they always run. If should be spraying errors about "hit.transform is NULL
" after each miss.
The short red lines are usual. Unlike raycasts, Debug.DrawRay has the direction and distance together (transform.forward*10
will make a longer line.)
I'd guess the code is otherwise working perfectly, but your direction
empty is in the wrong spot. Try putting a cube (with no collider) on it, for a visual, or just select it while running in Scene view, or check every rotation while you're running. You might see something with the blue-arrow unexpectedly going down, putting "far forwards" exactly where the red lines are coming from.
[Edit: new from here down] To really go nuts, check whether direction
is what you think it is (make it a public global & check inspector while running.) Try printing Debug.Log("fwd="+fwd);
to make sure fwd isn't really underground.
Answer by Paum · Nov 08, 2011 at 05:14 PM
Thanks, I had not seen the semi-colon there.
Now the Direction is selected, and i dont know why the Ray is so far from it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613034526im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to place an object in the direction of a raycast 1 Answer
Raycast won't hit Collider 1 Answer
Make Raycast ignore anything that "Isn't" my player(Solved) 1 Answer
Wall running using raycasting. 2 Answers
Layermask doesn't seem to work 2 Answers