- Home /
Why is this Raycast not working ?
I've checked various examples and tried to replicate them but for some reason the raycast doesn't seem to work. And yes, I do have objects tagged as 'wall'.
RaycastHit hit;
bool wRay;
void Update () {
if (Input.GetKey (KeyCode.W)) {
Physics.Raycast(transform.position, Vector3.left, out hit, 0.01f);
wRay = Physics.Raycast(transform.position, Vector3.left, out hit, 0.01f);
Debug.DrawRay(wRay, Color.red, 0.01f);
if (wRay)
{
if(hit.transform.tag == "wall")
{
gameObject.transform.rotation = Quaternion.Euler(0,270,0);
}
}
}
}
How does it not work? Does it not detect the tagged object? Does it cast in the wrong direction? Does it not cast at all?
Answer by NickP_2 · Sep 10, 2014 at 10:46 AM
the third parameter (0.01f) is the length of the ray, note that 0.01f really isn't a lot! (It might not even leave the NPC/Player's model, if there's one.) Have you tried deleting that parameter and just use an infinite ray?
Just for performance's sake, store the ray in a variable. Something like:
Ray ray;
RaycastHit hit;
ray.origin = transform.position;
ray.direction = Vector3.left;
if(Physics.Raycast(ray, out hit) && hit.transform.tag == "wall")
{
//remaining code...
}
Debug.DrawRay(ray, Color.red);
The length of the ray was apparently too small. I was assu$$anonymous$$g the length to ins$$anonymous$$d be the duration of the ray for which it will be displayed, as in Debug.DrawRay. Thanks !
Answer by jsleek · Oct 16, 2017 at 10:47 AM
For anyone else reading this and their raycast still isn't working,
Make sure you have a mesh collider on the surface you are aiming at. The raycast needs to collide with something.
That's what got it working for me.
Answer by khenkel · Sep 10, 2014 at 10:47 AM
There can be a few reasons why your Raycast "doesn't seem to work". I don't know what exactly doesn't work, so I'll provide some ideas:
First of all, Physics.Raycast returns a bool, so you might want to poll it directly (" if(Physics.Raycast(transform.position, Vector3.left, out hit, 0.01f)") instead of doing it by saving it temporarily. The "hit" variable will then contain everything you need about your Raycast.
The distance seems to be very short. Keep in mind that the raycast is sent from transform.position, which means the origin of your object. For testing try out "Mathf.Infinity" instead.
You're sending it in the Vector3.left direction, which is absolute, it will always be the same direction. If you want it to be relative to your object, use "this.transform.left" instead. (correct me if I'm wrong here)
EDIT:
Whoops, "this.transform.left" doesn't exist. Then use "-(this.transform.right)". :)
Your answer
Follow this Question
Related Questions
Holding object not working. Raycast, and first person. 1 Answer
Raycast starts ignoring gameobject after a few seconds 0 Answers
My rotate dont work, using raycast, C# 1 Answer
RTS Controller? 0 Answers
Raycast ignoring tags problem 1 Answer