hey guys I am trying to destroy a specific object coming towards me when touch it just like guitar hero.
my code right now just destroy wherever I touch
I am new to coding so I appreciate a basic explanations thx you
{
private float forcemult = 200;
private Rigidbody rb;
Ray ray;
RaycastHit hit;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
rb.AddForce(transform.forward * forcemult * Time.deltaTime);
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
}
if (Physics.Raycast(ray, out hit ))
{
Debug.Log("hit something");
Destroy(hit.transform.gameObject);
}
else
{
if (Input.touchCount > 0)
{
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
}
}
CodePudding user response:
You can give your gameobject a specific tag and then check if the gameobject you hitted has this tag.
Something like:
if(hit.collider.tag == "Enemy") {
// Do Stuff
}
This is the simplest way to check for a collision with a specific gameobject.
You can also check if the name of the gameobject you hitted has the name you want for example:
if(hit.collider.gameobject.name == "Enemy01") {
// Do Stuff
}
I personally don't like the name checking variant, because it only works reliably in specific situations.
Another method you can use is attaching a script to the gameobject and then check if the gameobject has this script:
YourScript script = hit.collider.gameobject.GetComponent<YourScript>();
if(script != null) {
// Do stuff
}
This is probably the best way of handling this because you can instantly call an event after the collision happened.
CodePudding user response:
The part of the code that is responisble for detecting objects is if (Physics.Raycast(ray, out hit ))
. You can add two additional inputs to this method to destory the objects you desire. The first input is maxDistance
which is the max distance the ray should check for collisions, the second one is layerMask
which is a Layer mask that is used to selectively ignore colliders when casting a ray.
Define a new layer in unity and assign it to the objects you wish to desotry.
click on edit layers:
Define a serialized field of type layerMask and assign the layer (Target in my case) you defined in the inspector:
// assign in the inspector
[SerializeField] private LayerMask toHit;
// your code
//..
// you can define the hit variable in the if statement if you
// don't need it somewhere else using the syntax I have used,
// otherwise remove the var keyword, the 100 is the maxDistance value,
// use any value you wish. toHit determines what physic engine selects
// and what ingores.
if(Physics.Raycast(ray, out var hit, 100, toHit))
{
Debug.Log($"hit: {hit.transform.name}");
Destroy(hit.transform.gameObject);
}