- Home /
How to get a few touches on sprites?
I develop a platformer-game. How can I receive more than one touches on sprites on my device? On my mobile game I can't process more than one touches, for example I need to run and jump at the same time, you know ;D
Answer by MichaI · Jan 06, 2019 at 02:23 PM
From https://docs.unity3d.com/Manual/MobileInput.html you can read example:
foreach (Touch touch in Input.touches) { if (touch.phase == TouchPhase.Began) { // Construct a ray from the current touch coordinates Ray ray = Camera.main.ScreenPointToRay (touch.position); if (Physics.Raycast (ray)) { // Create a particle if hit Instantiate (particle, transform.position, transform.rotation); } } }If you want to test ray against 2d colliders you can do something like this:
foreach (Touch touch in Input.touches) { if (touch.phase == TouchPhase.Began) { Vector3 pos = Camera.main.ScreenToWorldPoint (touch.position); RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero); if (hit != null && hit.collider != null) { // Do something with hit Debug.Log ("I've hit "+hit.collider.name); } } }
Answer by unity_FUTS41AFlwuXDQ · Jan 14, 2019 at 04:01 PM
Thank you so much, Michal. I have only one problem: when I press two buttons at once, one of them just hangs up until you press somewhere else. How to fix it?
I don't know how exactly your buttons works, but I think you can simply remove if statement wich check for touch phase, so it executes for every touch phase (in this case you have to have button released as default whenever it isn't holded):
foreach (Touch touch in Input.touches) { Vector3 pos = Camera.main.ScreenToWorldPoint (touch.position); RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero); if (hit != null && hit.collider != null) { // Do something with hit Debug.Log ("Press and hold button "+hit.collider.name); } }, or you can add if statement for touch phase "Ended" :
foreach (Touch touch in Input.touches) { if (touch.phase == TouchPhase.Began) { Vector3 pos = Camera.main.ScreenToWorldPoint (touch.position); RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero); if (hit != null && hit.collider != null) { // Do something with hit Debug.Log ("Press button "+hit.collider.name); } } if (touch.phase == TouchPhase.Ended) { Vector3 pos = Camera.main.ScreenToWorldPoint (touch.position); RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero); if (hit != null && hit.collider != null) { // Do something with hit Debug.Log ("Release button "+hit.collider.name); } } }Also if you using this for buttons, you could use ins$$anonymous$$d built in UI buttons with your sprites on it.
Your answer
Follow this Question
Related Questions
Getting my character to slide 2D platformer 0 Answers
2D Combo Attack 1 Answer
Unity 2D Platformer Collision Issue 1 Answer
How to create a blood splatter effect 1 Answer
2d Platformer sprites background 1 Answer