DjLeChuck
DjLeChuck

Reputation: 378

Unity - Raycast hit, wrong collider

Here is my code:

using UnityEngine;

public class InputController : MonoBehaviour {

    void Update() {
        if (Input.GetMouseButtonUp(0)) {
            var hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

            if (hit.collider != null) {
                var e = hit.collider.gameObject;

                Debug.Log(e.transform.position.x + ":" + e.transform.position.y);
            }
        }
    }
}

When I click/touch a cell, sometimes the hit is good and the cell is revealed, sometimes the hit is always false (it's like I touch the wrong cell) and sometimes it depends of the position of my click (see images below).

I click the left part of the cell, the console says I click the cell on the left. wrong raycast

I click the right part of the cell, the console says I click the right cell (and reveals it). In this case it's left / right but it can be top / bottom, a corner... good raycast

I don't know if my problem is very well explained sorry, and my English is not perfect... Don't hesitate to ask me more details!

Upvotes: 0

Views: 946

Answers (2)

Sudhir Kotila
Sudhir Kotila

Reputation: 677

I Guess Here is problem with collider overlaping. you have to just reset all the collider and check it, is it overlaping on any object or not?

you can check colider on gamemode , turn on "Gizmo". so you will see all the collider and check it again is it overlaping on there or not ?

Upvotes: 0

DjLeChuck
DjLeChuck

Reputation: 378

Ok I find the problem.

The left cell had a scale of 2 so it overlaps the right cell.

Upvotes: 0

Related Questions