- Home /
Raycasting error?
Basically I have an object which sends 2 raycasts out downwards to detect if anything is hit, I'm using this code:
if (Physics.Raycast (Vector3(transform.position.x + 0.3, transform.position.y, transform.position.z), -Vector3.forward, hit, ydist, layerMask) || Physics.Raycast (Vector3(transform.position.x - 0.3, transform.position.y, transform.position.z), -Vector3.forward, hit, ydist, layerMask)) {
}
They're hitting objects but not in the correct direction, it's odd because I also have rays firing out upwards, left and right and they all seem to be working correctly. The image below shows what I mean, the object with the x on it is the object which the script is contained on and the red line denotes the direction that the raycast should be fired (using Debug.Draw). The box which is outlined in red is the box which is hit which clearly isn't right.

Any help or ideas would be GREATLY appreciated.
Edit Note : Even if I reduce both of the "0.3's" to 0 it still doesn't work so thats not the problem :(
Vector3.right??? Don't you want Vector3.down? Admittedly I know nothing about the coordinate system you are using.
Sorry, I posted the wrong section of code I was thinking about firing right so much ^^. Updated :)
Now you're casting the ray backwards (-Vector3.forward). Is that what you consider the down side? It should be -Vector3.up in a regular coordinate system
It's viewed from a top down perspective so I want to cast along the z axis :)
If the ground in your game is the XY plane, the Z axis should be Vector3.forward, no? Anyway, that box is apparently out of the down direction. Could the box and its collider be misaligned? Raycast checks the collider, not the mesh. And which collider the box have? Box or mesh collider? $$anonymous$$esh colliders can produce some unexpected results, maybe due to incorrectly generated bounds. Another possibility could be some object childed to the box intercepting the ray.
Answer by PaulUsul · Jul 29, 2011 at 09:19 AM
It's because you are firing towards vector(0,-1,0) from your position, making skewed lines instead of straigh lines from your position. something like this(C#)..
Vector3 pos1 = transform.position;
pos1.x += 0.3;
Vector3 dir1 = pos1 - Vector3.forward;
Vector3 pos2 = transform.position;
pos2.x -= 0.3;
Vector3 dir2 = pos2 - Vector3.forward;
if (Physics.Raycast (pos1 , dir1 , hit, ydist, layerMask) ||
Physics.Raycast (pos2 , dir2 , hit, ydist, layerMask)) {
}
Did this approach work, by firing from the target towards it's axis and not world space coords..?
Your answer
Follow this Question
Related Questions
My raycast is not always in the forward direction. 1 Answer
Problem with raycasting when checking neighbouring objects? 0 Answers
What is the best way to navigate through a grid based level using Raycasting ? 2 Answers
How could I combine melee weapons and rays? 1 Answer
Someone can help with Ray/Collide? 1 Answer