bloobchube
bloobchube

Reputation: 39

Unity2D: How to check if a sprite is clicked/touched

I am making a 2D platformer in Unity for iOS, and I need to make buttons so the user can move, but for some reason, the script I made is not working. Also, the script I am putting in is just for the Left button, but the Right and Jump scripts work the same way.

Code:

using UnityEngine;
using System.Collections;

public class Left : MonoBehaviour {

public GameObject player;
public GameObject button;

void Start () {

}

void Update () {
    if (Input.GetKey (KeyCode.A)) {
        player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
        player.transform.position+=Vector3.left / 30;
    }



    if (Input.touchCount > 0){
        foreach(Touch touch in Input.touches){
            Collider2D col = button.GetComponent<Collider2D>();

            Vector3 tpos = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 0));

            if(col.bounds.Contains(tpos)){
                Debug.Log ("left");
                player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
                player.transform.position+=Vector3.left / 30;
            }
        }
    }
}

void OnMouseOver(){
    Debug.Log ("left");
    player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
    player.transform.position+=Vector3.left / 30;
}

void OnMouseUp(){
    player.GetComponent<PlayerAnimator> ().animationState = MovementState.idleLeft;
}

}

Upvotes: 0

Views: 2525

Answers (1)

Cenkisabi
Cenkisabi

Reputation: 1076

Don't use OnMouseOver for android application. It isn't usable on touch devices. But instead of it, OnMouseDrag function will work.

void OnMouseDrag(){
    Debug.Log ("left");
    player.GetComponent<PlayerAnimator>().animationState = MovementState.moveLeft;
    player.transform.position+=Vector3.left / 30;
}

Edit: Because OnMouseOver is called when position of mouse is over object but not clicked. Otherwise OnMouseDrag is called when position of mouse is over object and clicked. In mobile devices OnMouseOver situation isn't possible.

Upvotes: 2

Related Questions