- Home /
Question by
Zachary Hoffman · Jun 17, 2014 at 07:07 PM ·
touch
How do detect when an Object is touched
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);
}
Comment
Answer by Graham-Dunnett · Jun 17, 2014 at 07:09 PM
You mean something like the third example on this page:
http://docs.unity3d.com/ScriptReference/Input.GetTouch.html
???
I tried to implement that and am testing it now but I'm doing it on my pc and its not working. Do mouse clicks count as touches when the build setting is android or do I have to set it to a specific setting?
Your answer
![](https://koobas.hobune.stream/wayback/20220613151802im_/https://answers.unity.com/themes/thub/images/avi.jpg)