【问题标题】:Unity2D: How to check if a sprite is clicked/touchedUnity2D:如何检查精灵是否被点击/触摸
【发布时间】:2015-08-24 18:39:18
【问题描述】:

我正在 Unity for iOS 中制作 2D 平台游戏,我需要制作按钮以便用户可以移动,但由于某种原因,我制作的脚本无法正常工作。另外,我输入的脚本仅适用于左按钮,但右和跳转脚本的工作方式相同。

代码:

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;
}

}

【问题讨论】:

    标签: c# ios button unity3d touch


    【解决方案1】:

    不要将 OnMouseOver 用于 android 应用程序。它不适用于触摸设备。但不是它,而是 OnMouseDrag 函数将起作用。

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

    编辑:因为当鼠标的位置在对象上但未单击时调用 OnMouseOver。否则,当鼠标的位置在对象上方并单击时调用 OnMouseDrag。在移动设备上 OnMouseOver 情况是不可能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多