2

I have a bomb and want it to explode when touched. I just tried implementing this with ray-casting but something isn't working. I'm using unity 2d settings.

Also I'm programming this on a computer(of course) so is there some setting I have to set to make it recognize mouse clicks as touches?

#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);
}
Zachooz
  • 535
  • 1
  • 12
  • 25
  • http://answers.unity3d.com/questions/359754/how-can-i-detect-touch-on-anroid-or-iphone.html / http://docs.unity3d.com/ScriptReference/Input-touches.html – Marco Acierno Jun 17 '14 at 19:48
  • @MarcoAcierno I tried that but something isn't working :/ look at my updated question please :) – Zachooz Jun 17 '14 at 19:54
  • modern answer: https://stackoverflow.com/questions/40323677/using-unity3ds-ipointerdownhandler-approach-but-with-the-whole-screen – Fattie Jan 23 '19 at 16:41

1 Answers1

0

The OnMouseDown actually gets raised on touch as well. It, of course, limits your ability to track the finger Id, but if you don't need it then this is perfect since it does allow you to use it on both PC and touch devices with no extra code.

Formic
  • 650
  • 5
  • 7