Alternative method to destroy lasers

Hi, instead of adding a new box collider, I just created a script for the lasers and checked that, relative to the camera world view, the laser is outside the max y range, and if it is destroy itself:

Script PlayerLaser:

void Update()
    {
        if (transform.position.y > Camera.main.ViewportToWorldPoint(new Vector2(0,1)).y)
        {
            Destroy(gameObject);
        }
    }

and I could check that the laser is outside the (0,1) boundary for x too, in case we add another type of laser that goes sideways or diagonal instead of just up.

Is there any downside to this approach?

Thanks!
Luis.

1 Like

Hi Luis,

Welcome to our community, and good job on developing your own solution! :slight_smile:

To me, your idea makes sense, and the code looks fine. The only thing I would change is Camera.main. I would cache the reference in an instance variable in the Start method. And in Update, I would use the variable. Why? Because Camera.main looks for the camera with the “Main Camera” tag whenever Camera.main gets executed. See the API. Apart from this little detail, I think your code is performant and solves the problem. Well done! :slight_smile:


See also:

Hi Nina,

Indeed, I forgot to think about caching the reference since it will avoid unecessary API calls and transform calculations on each frame. Thanks for the reply and to tell me that the code is ok! :slight_smile:

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

Privacy & Terms