I tried this code:
if (Input.touchCount > 0)
{
var ray = Camera.main.ScreenPointToRay (Input.GetTouch(0).position);
var hit: RaycastHit;
if (Physics.Raycast (ray, hit))
{
if (hit.collider.tag == "Enemy")
{
Destroy(hit.transform.gameObject);
}
}
}
But nothing happens when I play my game on the phone. I just want to destroy objects from prefabs when I touch them. They just fall down like raindrops.
What should I do?
EDIT:
Here’s what works (Thank you JeffreyD!):
if (Input.touchCount > 0)
{
var hit : RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint((Input.GetTouch(0).position)), Vector2.zero);
if(hit.collider != null)
{
Destroy(hit.transform.gameObject);
}
}
I’d do something like…
`
bool myDebug = false; // set to true to see debug info in console
void Update()
{
int fingerCount = 0;
RaycastHit hitInfo;
Ray rayOrigin = Camera.main.ScreenPointToRay(Input.mousePosition);
//Debug.DrawRay(transform.position, vfwd * 20, Color.red);
foreach (Touch touch in Input.touches)
{
if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
fingerCount++;
}
if (fingerCount > 0)
{
if (myDebug)
{
Debug.Log ("FingerCount is : " + fingerCount);
}
if (Physics.Raycast(rayOrigin, out hitInfo, 20))
{
if (myDebug)
{
Debug.Log("I see We hit ==> " + hitInfo.transform.name);
}
if(hitInfo.transform.tag == "Enemy")
{
if (myDebug)
{
Debug.Log("We hit the TARGET");
}
Destroy(hitInfo.transform.gameObject); // can add time delay as second argument
}
} // END if raycast
} // END if (fingerCount > 0)
}`
I’ve not tested this. Let me know if it works.
Thanks.
P.S. Link to touch info in docs Unity - Scripting API: Input.GetTouch
assign this code to the main camera,and drag the game object to cubes variable.and tag the gameobject with “new” tag.Tested in android phone.
using UnityEngine;
using System.Collections;
public class touch : MonoBehaviour
{
public GameObject cubes;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Input.touchCount >0)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
if (Physics.Raycast(ray, out hit))
if (hit.collider.gameObject.tag =="new")
{
Destroy(cubes);
//cubes.rigidbody.AddForce(Vector3.forward * Time.deltaTime *500);
}
}
}
}