Hi,
I’m beginner with Unity and I would like to create a tiled map game.
In order to select a character in my scene, I’m using RayCast2D. After several researches, here is how I implemented it :
void Update () {
Vector2 rayPos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
RaycastHit2D hit = Physics2D.Raycast(rayPos, Vector2.zero, 0f);
if (hit)
{
GameObject hitObject = hit.collider.gameObject;
if (Input.GetMouseButtonDown (0)) {
Debug.Log ("Selected object = " + hitObject.name);
}
}
}
My RayCast2D seems to work well but I have a real problem and despite some researches, I didn’t find any solution to it. Here is the problem :
My map is a two dimensions array and each item of the array is a tile equipped with by a Collider component (Box Collider 2D). With the previous script, when I click on a tile of my map, the console logs the name of the object which contains the BoxCollider2D hitted. All works perfectly.
The problem comes when I insert a character (and more generaly, another gameobject) on my map. Indeed, when I place my character (equipped with a Circle Collider 2D) on a tile, both colliders (Circle Collider and Box Collider) are logically superimposed but thanks to the Sorting Layer function of the Sprite Renderer, I’m able to place the character above the tile.
Visually, all works perfectly but when I click on the character, the RayCast2D just hits the tile and not the character. And the more craziest thing is that this problem appears only on specific tiles ! For example, if the character is placed on the tile [2,3] (coordinates), the RayCast2D hits the character but if the character is placed on the tile [3,3], the RayCast2D just hits the tile and not the character.
As beginner, I don’t know if the solution is obvious or not, so if you need more information about this problem, I can provide some screenshots of the scene and why not a mini-video.
Thank you in advance for your answers !
Axel.
PS : Sorry if my english isn’t perfect, I’m not a native english speaker.