Raycast a touch on a Gameobject

Hi,
My problem is rather long so I will explain it in detail.
The idea of my game is, that raindrops spawn randomly over the screen and then fall.
The player must proceed to tap on the raindrops to let them burst and gain points.
So when the player touches the screen , a Raycast gets created and checks for objects, and when the object’s tag is “Tropfen” I want to destroy it.
My problem is that my Raycast doesn’t seem to detect anything and therefore my raindrops don’t get destroyed as they should.

Here’s my Raycasting Script, which is attached on the MainCamera:

public class GameplayInput : MonoBehaviour
{
    Spawner spawner;
    GameObject TropfenObject;

    // Start is called before the first frame update
    void Start()
    {
        spawner = FindObjectOfType<Spawner>();
        TropfenObject = spawner.tropfen;
    }

    // Update is called once per frame
    void Update()
    {
        GetInput();
    }

    private void GetInput()
    {
        if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
        {
            Ray raycast = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
            RaycastHit raycastHit;
            if (Physics.Raycast(raycast, out raycastHit))
            {
                Debug.Log("Something Hit");

                if (raycastHit.collider.CompareTag("Tropfen"))
                {
                    Debug.Log("object clicked");
                    TropfenObject.GetComponent<Tropfen>().TropfenDestruction();
                }
            }
        }
    }
}

and here’s the method that get’s called , when the raindrop is destroyed:

public void TropfenDestruction()
    {
        if (isMuted != 0)
        {
            AudioSource.PlayClipAtPoint(source.clip, transform.position);
        }
        GameObject effect = Instantiate(particleEffect, transform.position, Quaternion.identity) as GameObject;
        Destroy(effect, 2f);
        gameplay.IncreaseScore(1);
        Destroy(gameObject);
    }

Hi Draz,

Welcome to our community. :slight_smile:

Do the drops game objects have got a collider attached?

Yes, they have a CapsuleCollider2D attached

Does the raycast hit something? If so, log the name of the object it hit into your console.

My Raycast doesn’t hit anything. Tried to log the name of the collider into the console, but nothing shows up in it.

Test the Raycast of the Physics2D and make sure the ray is long enough.

https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html

I aligned every GameObject infront of my camera to a uniform Z-Axis value and used a Raycast2D.
Now the Raycast hits objects and everything works now!
Thanks

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.