- Home /
Physics2D.Raycast "Vector3 to Vector2 conversion" [Solved]
Hi guys, I am casting a 3D ray from the screen to the touch position. Unfortunately my game objects are sprites with 2D Colliders and a 3D ray is not colliding with them. Then I though I would cast a 2D ray to see what happens.
Here is the code:
Ray ray = Camera.main.ScreenPointToRay(touch.position);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, rayLength);
if (hit)
{
// Do some stuff
}
The signature of the Raycast method is as follows Physics2D.Raycast(Vector2 origin, Vector2 direction, float distance). I don't understand why the code is compiling and the effect is the same as casting a 3D ray, because I am passing 3D vectors to the method, but the method takes 2D vectors as parameters?
Answer by Kiwasi · Jul 02, 2014 at 10:20 AM
If you check out the documentation for Vector2 it has an implicit conversion to and from Vector3. In essence it does this by discarding or setting the z to zero as appropriate. So be warned that if you cast a from a Vector3 to a Vector2 and back again you will loose the z component.