- Home /
How to click within a game objects collider?
So I have created a 10x10 grid of squares from quads with their own separate BoxCollider2D and I wanted to, whenever I'm within one of the squares and when it's clicked, to print a statement (any statement would do, it's just to see if it's working).
Here is the code for my Update function:
void Update () {
if (boxColl.bounds.Contains(Input.mousePosition)) {
if (Input.GetMouseButtonDown (0)) {
print ("Hello");
}
}
}
boxColl is a variable that I instantiated earlier to get the component BoxCollider2D.
Now the problem is whenever I click, it doesn't do anything so I was wondering is that because of the read-only property of the Input.mousePosition (because I read the documentation and it returns a Vector3 which you need for the bounds.Contains()) or is it something about colliders and bounds that I don't understand?
Thanks for advance guys!
Use On$$anonymous$$ouseDown? http://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.On$$anonymous$$ouseDown.html
I could be wrong, but I think the mouse position always has a 0 depth value. Basically, it's 2D. I think people have used raycasting in the past. So, Click, and Cast a ray out at mouse x,y,with a Z forward from camera. Then check the collision, if it hits one of your cubes, begin the interacting code. Something along the lines of that.
-Dwayne Pritchett
Wow, I can't believe how simple that was with On$$anonymous$$ouseDown, thanks so much, that works!
@Dwayne, the raycasting sounds cool, I will try that too just for fun, thanks!
I didn't think it would be as simple as On$$anonymous$$ouseDown either, hm... learn something new everyday.
Your answer
Follow this Question
Related Questions
Personaje cambie de sprite al teleportarse [Characters change sprite to teleport] 0 Answers
Jump doesn't work while changing 2d colliders 0 Answers
Input.GetMouseButtonDown only works for 10seconds 2 Answers
What's wrong with OnCollisionEnter? 2 Answers
Synchronizing Fake Mouse Position with Actual Mouse Movement 0 Answers