Mouse click doesnt seem to be hitting the right collider

I’m new to using raycasts and I think everything in script is working as it should, except the object I click on is not the object that gets effected. Basically There is a Card Class and a Deck class and I want the user to click on one of the cards that are displayed and have it move from one Deck to another. I am guessing I did something wrong with either my Ray creation or my RaycastHit2D creation. Any Ideas?

public delegate void ClickAction(Card card);
	public static event ClickAction OnClicked;
	void Update () {
		if (Input.GetMouseButtonDown (0)) {
			Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
			RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction);
			Debug.Log (hit.point);

			if (hit.collider != null) {
				Card cardScript = hit.collider.GetComponent<Card>();
				if(cardScript){
					Debug.Log("Got Card");
					if(OnClicked != null){
						OnClicked(cardScript);
					}
				}
			} else {
				Debug.Log ("Didn't click game object");
			}
		}
	}

and if it matters the OnClicked event is …

  void OnEnable(){
    		ClickCard.OnClicked += MoveCardToBidHand;
    	}
    	void OnDisable(){
    		ClickCard.OnClicked -= MoveCardToBidHand;
    	}
    	public void MoveCardToBidHand(Card card){
    		Debug.Log ("Method was fired");
    		bidHand.getList ().Add (card);		
    		hand.getList ().Remove (card);
    		hand.getList ().TrimExcess ();
    	}

`

what object is getting clicked; is it one that is in the way, or a parent, or something way off?

I worked around a similar issue by offsetting my gameobjects slightly in z (top to bottom) and then using Physics2D.GetRayIntersection (instead of Physics2D.Raycast) RaycastHit2D hit = Physics2D.GetRayIntersection(ray, distance, layermask); http://docs.unity3d.com/ScriptReference/Physics2D.GetRayIntersection.html Not sure if this is suitable for your situation, but it works well for me.

1 Answer

1

Try putting your card GameObject onto a layer and using a layer mask and also tagging your card as “Card”

LayerMask layerMask = 1 << 8;  //8  is normally the first slot that you can add in layers, use whatever number layer your card is on


if (Input.GetMouseButtonDown(0)) {

				RaycastHit2D hitCheck = Physics2D.Raycast(_camera.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, layerMask);

                            //make sure you're actually clicking on a collider
				if(!hitCheck.collider)  
					return;
                           //Check tag of gameObject for collider is "Card"
				if(!hitCheck.collider.gameObject.CompareTag("Card")) 
					return;

etc...
}

Hope this works.

Ah ok, I think I might what's happening. Do you have this code attached to each card or the camera? the ray cast should be a script on the camera, if it's on each card it can get triggered for each card, rather than just the first card hit.