- Home /
Touch Detection in 2D Game
Using following code I can able to detect touch of 3d box collider but when I attach Box Collider 2D, the code does not work.
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{}
So how to detect touch for Box Collider 2D?
Answer by robertbu · Jan 18, 2014 at 05:45 PM
For 2D and an Orthographic camera, you can do it like this:
void Update () {
Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero);
if (hit != null && hit.collider != null) {
Debug.Log ("I'm hitting "+hit.collider.name);
}
}
There is another line or two if you are using a Perspective camera.
Thanks for your answer, I will check this code and reply to you shortly.
If I want a android touch position, what do I put ins$$anonymous$$d of the Input.mousePosition?
I have already tried: - Input.GetTouch(0).position - new Vector3(touch.position.x , touch.position.y, 0);
you have to use Camera.main.ScreenToWorldPoint (Input.mousePosition);
to get touch position.
Answer by vfxjex · Sep 17, 2014 at 08:50 AM
why not use this instead?
JavaScipt
function OnMouseOver () {
if(Input.GetMouseButtonDown(0)){
//your code
}
}
Because this whole screen touch detect not particular object.
Answer by JoaoOliveira · Jan 17, 2014 at 02:24 PM
Ok, I recently had to implement this very same functionality. I had code for 3D colliders and didn't want to change it too much. So in 3D I was doing this:
var ray = Camera.main.ViewportPointToRay(new Vector3(touch.Position.x, touch.Position.y, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit)){
//Do stuff
}
The equivalent in 2D is:
var ray = Camera.main.ViewportPointToRay(new Vector3(touch.Position.x, touch.Position.y, 0));
var hit = Physics2D.GetRayIntersection(ray);
if (hit.collider != null) {
//Do stuff
}
If I want to convert my statements for 2d games then what will be?Because all classes are available in 2d.
Ins$$anonymous$$d of:
if (Physics.Raycast(ray, out hit))
You use:
if (Physics2D.Raycast(ray, out hit))
You mislead in this thing there is no function available in Physics2D.
Ok I didn't remember it wasn't exactly the same.
But in any case, it's the same principle as in 3D: if you check the input arguments in the link I provided you should be able to adapt your code accordingly.