RayCastHit2D fails to hit script generated grid
This issue has been asked and answered several times before, but for some unknown reason, it doesn't work for me (beginner). I am generating a 2D grid with a C# script to create a variable size game board. Starting point is this tutorial procedural grid. To interface with the grid with the mouse, I want to cast a ray at mouse position. There is a 3D example here Tile maps #5, however this does not work in 2D mode (and the syntax is deprecated). First challenge (and perhaps error?) is that I have to add a meshcollider to the procedural grid script (ref. 1), the only way I get that to work is with gameObject.AddComponent<MeshCollider>().sharedMesh = mesh;
however this is not how the meshfilter
and meshrender
are added, so this may not be the right way to do it. It also differs from ref. 2, but other ways give an error that a script is trying to access a collider that is not defined. I have tried many variations of the RayCastHit2D
, but none of them generates a hit with the collider.
My most recent failed attempt is shown below (mouse script). To limit the size of this post I have added the Grid.cs code as an attachment.Grid.zip. Also attached is a screen dump.
Question: how can I get the RayCastHit2D to work on this particular implementation? Sorry for the long post, it's my 1st week with Unity...
void Update () {
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hitInfo = Physics2D.Raycast(mousePos, Vector2.zero);
//Debug.Log(hitInfo.collider);
if (hitInfo.collider != null)
{
Debug.Log(hitInfo.point);
GetComponent<Renderer>().material.color = Color.red;
}
else
{
//Debug.Log(hitInfo.point);
GetComponent<Renderer>().material.color = Color.green;
}
}
Answer by hexagonius · Mar 12, 2016 at 04:26 PM
The MeshCollider is a 3D physics component. you either use the PolygonCollider2D component, or raycast in 3D. size note, 2D raycast works from the side only, since there's no z axis. use overlappoint for that kind of check when using 2D stuff