I need to be able to detect when an object (2D sprite) is about to move off screen and stop it from doing so. I’m currently using the following to check the screen boundry:
if (cam.WorldToViewportPoint(transform.position).x > 1) //do stuff
It works, but this type of conversion seems rather expensive… four such calls and I’m seeing a 30% fps drop on an older machine!
So what’s another way to pull this off?
I need to be able detect bounds, and it needs to work with both orthographic and non-orthographic cameras, and it needs to work regardless of screen size (so my game can be played at different resolutions).
Well it turns out that WorldToViewportPoint was NOT causing the slowdown. In fact, I can do 500 of these per frame with very little slowdown. Even when these calls are turned off, the Statistics screen is showing the large drop in fps whenever I move my object (a basic cube).
So it looks like the slowdown is caused by the act of moving the object itself, whether I call transform.Translate or increment transform.position. Not sure why, but it could be that I was doing these tests on a machine with a G5 processor. Unity doesn’t seem to like those, for some reason…