Reputation: 156
I have a written a multi-touch system that works correctly with objects that have collider2d (use them as buttons) and I can move the player in my Android phone.
But when I use an image from the UI canvas system and add this code to the image, it doesn't detect anything.
Here is my code:
using UnityEngine;
using System.Collections;
public class Jump : MonoBehaviour {
public float jumpForce;
private GameObject hero;
void Start () {
hero = GameObject.Find("hero");
}
void Update () {
if (Input.touchCount > 0)
{
Touch[] myTouches = Input.touches;
for(int i = 0; i < Input.touchCount; i++)
{
if(Input.GetTouch(i).phase == TouchPhase.Began)
{
CheckTouch(Input.GetTouch(i).position, "began");
}
else if (Input.GetTouch(i).phase == TouchPhase.Ended)
{
CheckTouch(Input.GetTouch(i).position, "ended");
}
}
}
}
void CheckTouch (Vector3 pos, string phase)
{
Vector3 wp = Camera.main.ScreenToWorldPoint (pos);
Vector2 touchPos = new Vector2 (wp.x, wp.y);
Collider2D hit = Physics2D.OverlapPoint(touchPos);
if(hit.gameObject.name == "JumpButton" && hit && phase == "began")
{
hero.rigidbody2D.AddForce(new Vector2(0f, jumpForce)); //Add jump force to hero
audio.Play ();
}
}
}
Upvotes: 0
Views: 3069
Reputation: 13327
You don't have to work with touches yourself anymore. Just implement IPointerClickHandler interface and make sure you have EventSystem and an appropriate raycaster present in the scene.
Upvotes: 1
Reputation: 1736
For Graphics items in canvas you need to use GraphicRaycaster instead of Physics2D using UnityEngine.UI
Upvotes: 2