【问题标题】:How to detect touch in Unity Game Engine (2D)如何在 Unity 游戏引擎 (2D) 中检测触摸
【发布时间】:2014-06-17 18:11:44
【问题描述】:

我有一个炸弹,我希望它一碰就爆炸。我只是尝试用光线投射来实现它,但有些东西不起作用。我正在使用统一的 2d 设置。

我也在电脑上编程(当然)所以我必须设置一些设置才能让它将鼠标点击识别为触摸?

#pragma strict
var explosion:GameObject;


function Update () {
    for (var i = 0; i < Input.touchCount; i++) {
        if (Input.GetTouch(i).phase == TouchPhase.Began) {

            // Construct a ray from the current touch coordinates
            var pos:Vector3 = Camera.main.ScreenToWorldPoint (Input.mousePosition);
            var hitInfo:RaycastHit2D = Physics2D.Raycast(pos, Vector2.zero);
            if (hitInfo != null && hitInfo.collider != null) {
                Debug.Log ("I'm hitting "+hitInfo.collider.name);
                var whatsHit:GameObject = hitInfo.collider.gameObject;

                if(whatsHit.CompareTag("bomb")){
                    whatsHit.GetComponent(BombScript).Explode(whatsHit.transform.position);
                }
            } else {
                Debug.Log("hitting nothing");
            }
        }
    }
}

function Explode(pos:Vector3){
    GameObject.FindGameObjectWithTag("GameController").GetComponent(BombSpawner).spawnBomb = true;
    Instantiate(explosion, pos, Quaternion.identity);
    Destroy (this.gameObject);
}

【问题讨论】:

标签: unity3d unityscript


【解决方案1】:

OnMouseDown 实际上也会在触摸时升起。当然,它会限制您跟踪手指 ID 的能力,但如果您不需要它,那么这是完美的,因为它允许您在 PC 和触摸设备上使用它,而无需额外的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多