Domanda

I have a number of sprites on top of each-other on the game board. When i use the mouse and select the sprite on top, all sprites under the mouse position is selected. My question is how to only select the sprite that I click on and not catch the ones below?

Here is the code i am using for my tests, attached to the sprites:

function Update () {
if(Input.GetMouseButtonDown(0)) {

    var theActualMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

//      print("ALL MousePosition: " + theActualMousePosition);

    if(collider2D.OverlapPoint(theActualMousePosition)) {

//          print("HIT theActualMousePosition: " + theActualMousePosition);

    print(collider2D.gameObject.tag);

    } 
}
}
È stato utile?

Soluzione

The results you are getting are completely expected as your code is placed on the GameObjects, what you should do is to push your script out of those objects or use another function than OverlapPoint (because overlap point does not check for collision it simply checks if you are in the bounds of an object, which means it is valid for all object)

Some ideas :

  • Using OnMouseDown should provide you with an event only for the first collider encountered
  • Using A raycast from the camera : Camera.ScreenPointToRay should be able to be used for a raycast and then to check only the first collider encountered
  • Using Layers depending on layer collision Order.

EDIT :

Or you could also cast the ray the other way around :

function Update () {
    if(Input.GetMouseButtonDown(0)) {

        var theActualMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector3 direction = (transform.Position-theActualMousePosition).normalized;
        Ray ray = Ray(transform.Position,direction)

        if(Physics.Raycast(ray) == null) {

            //Then there is nothing between the object and the camera then the object is the first one
            print(collider2D.gameObject.tag);

        } 

    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top