detecting touch on moving 2d gameobject

Hello !
I use this codes to detect touch on 2d gameobjects . but it doesn’t work on moving 2d gameobjects . Pleas help me to find the right code . thanks

public GameObject a;

public Transform ag;
float xsp;
float ysp;

if (Input.touchCount > 0) {
            Touch touch = Input.GetTouch (0);

            if (touch.phase == TouchPhase.Ended) {
                RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint ((touch.position)), Vector2.zero);

                if (hit.collider != null && hit.collider.transform.gameObject.name == "a") {
                    totalscore += 10;
                    a.SetActive (false);
                   

                }

            }
        }

My gameobject moves by this code :

void act3 () {

        xsp -= 0.5f*Time.deltaTime*speed1;
        ysp += 0.2f*Time.deltaTime*speed2;
        ag = new Vector2 (-4.2f+xsp , -3.1f+ysp);

        a.gameObject.transform.position = ag;

            }

Nothing about the above code would prevent touching when moving.

What happens if you disable the act3() function so that the object stops moving? Can you touch it then?

Correction: your second argument in the raycast is Vector2.zero. This argument is the direction to cast in. It should be the direction you want to raycast in, otherwise I think raycast’s function is undefined with no actual “cast” going on.

1 Like