- Home /
why Raycast2D doesn't work properly?
I am trying to know every time I clip up my mouse if there is a tile, but the Raycast2D method seems to work sometimes and some other times not. The next code does not work and returns a null RayCastHit2D:
LayerMask gridLayer = LayerMask.GetMask( "Grid" );
Ray2D ray = new Ray2D( eventData.position, Vector2.zero );
RaycastHit2D hit = Physics2D.Raycast( ray.origin, Vector2.zero, float.PositiveInfinity, gridLayer );
if ( hit.collider != null )
{
Debug.Log( "Hit a tile" );
}
But if a do it the next way the code works perfect, even if they have the same information (I debugged several times, and the information of eventData.position and Camera.main.ScreenPointToRay( Input.mousePosition ) is the same, so in both cases ray.origin provides the same Vector2):
LayerMask gridLayer = LayerMask.GetMask( "Grid" );
Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
RaycastHit2D hit = Physics2D.Raycast( ray.origin, Vector2.zero, float.PositiveInfinity, gridLayer );
if ( hit.collider != null )
{
Debug.Log( "Hit a tile" );
}
Why does this happen?, what is in the Ray class allowing the Raycast2D to works that its not in the Ray2D class?, is there any explanation to this? and finally, even if a I do it with a manually provided Vector2, the Raycast2D still does not work, so is there kind of mask that the Ray class have or something like that?
The thing is, that I need to be able to do it the first way, so the mouse input way its not a choise, i just by coincidense discover that it worked if do it like that but its not useful