I’m going crazy for a simple (maybe not) problem.
I’ve a RaycastHit2D that collides through a point, but when I try to access to the gameobject hit I get an unexpected result.
My code is pretty simple and I tried to draw my Raycast for debugging my error:
-
yellow: from origin to infinite
-
red: from origin to hit.point
public bool TryMatch() { Vector3 origin = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z + 1f); Vector3 end = new Vector3(origin.x, origin.y, int.MaxValue); Debug.DrawLine(origin, end, Color.yellow, 10f); RaycastHit2D hit = Physics2D.Raycast(origin, this.transform.forward); if(hit != null) { Debug.Log ("Touching " + hit.collider.transform.gameObject.name); Debug.DrawLine(origin, hit.point, Color.red, 10f); } return hit != null; }
As in the image, I start a ray from the “6 Spades” along the Z axis and we can see that the ray hits the “9 Clubs”.
But hit.collider.gameobject gives me “2 Hearts”… that is in front of the starting card and far from the ray.
