- Home /
How to detect a touch on Box Collider 2d in Unity 4.3
I am familiar with the 3D way of doing this
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.GetTouch (0).position);
if (Physics.Raycast(ray, out hit))
But when I have a Box Collider 2D , the Ray doesn't seem to hit, I tried using the Physics2D.Raycast but cannot get it also does not hit because its 2D ?
Thanks for any hints
Answer by noob101 · Nov 19, 2013 at 01:24 PM
Finally I managed to find the answer , in case somebody else who is not new to unity needs this the answer is
void Update()
{
if (Input.touchCount == 1)
{
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
Vector2 touchPos = new Vector2(wp.x, wp.y);
if (collider2D == Physics2D.OverlapPoint(touchPos))
{
//your code
}
}
}
Thanks for sharing. I was using the same method in 3D and got stuck when I tried with 2D.
How do you access that colliding object? Like if I wish to change its color or destroy it?
This script is ideally attached to the object so you will have direct access, but for other collisions you have to use OnCollisionEnter2D , see this http://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$onoBehaviour.OnCollisionEnter.html
I'm trying to run a foreach loop through touches in a separate script. I need to access the objects that I tap and change color. Could you help me out?
You can further simplify that since Vector3D inherits from Vector2D
if (Input.touchCount > 0)
{
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
if (collider2D.OverlapPoint(wp))
{
//your code
Debug.Log ("Hello");
}
}
Answer by Cervelx · Jun 04, 2017 at 10:02 PM
Hi thank you for the code, i have a question for you, with this script if i continue to press the screen the code is "repeating", the is a way to stop this, i mean i want to repeat my code but i want to tap again, i want to avoid that whit pressure the code is repeating...
Input.GetTouch() returns a Touch struct. If you want to only do something during the first frame in which the touch starts, check for the phase of the touch. you probably want TouchPhase.Began. See https://docs.unity3d.com/ScriptReference/Touch-phase.html
For example:
void Update()
{
if (Input.touchCount == 1)
{
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
Vector2 touchPos = new Vector2(wp.x, wp.y);
if (collider2D == Physics2D.OverlapPoint(touchPos) && Input.GetTouch(0).phase == TouchPhase.Began))
{
//your code
}
}
}
Answer by Akusan · Feb 02, 2020 at 04:32 AM
In case anyone is wondering what this should be for Unity 2019.3, 1st make sure the Game Object has a 2D Collider component, then add the following script:
void Update()
{
if (Input.touchCount > 0)
{
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
if (GetComponent<Collider2D>().OverlapPoint(wp))
{
//your code
Debug.Log("Hello");
}
}
}
Your answer
