I’m working on a 2D game where the player is only allowed to move within the scene / camera view and enemies (ships) would spawn outside of the camera view (the red dots) and travels across the screen depending on where they spawn (green arrows). My problem is that all the enemies are the same for the first wave of the game and therefore shares the same script. I had setup a random range for each enemy so it travels an X amount of distance but lets say the enemy on the right max distance is 20 across the screen and it’s still visible after traveling that length. However, if the enemy is spawn from the top traveling the full 20 distance (which is the max in the random range) it will move out of camera view. How can I handle this?
Question is: How do you want to handle this?
If I get you right, the enemies are supposed to travel a random distance, and some of them leave the screen when doing so.
Do you not want them to leave the screen? If not, what should they do instead?
Get a shorter maximum travel distance?
Or should it bounce back into the screen?
Well that is basically my problem. My enemies travel into the screen and some of them leave the screen when doing so due to the min and max random range. I didn’t have an exact solution how I would of handled it but would it be possible to somehow stop the enemy before the reach the edge of the screen? Another thing I just thought about after reading what you wrote is that maybe it would be better if I somehow bounce then back into the screen, but how would I go about doing that?
Depends on how you move your enemies.
If it’s via Rigidbody, you can simply place walls at the right positions and add a bouncy physic material either to the enemies or to the walls.
If you’r doing it somehow else, like with Transform.Translate, you have to give the enemies a script that checks whether or not the enemy is touching a screen wall. The upper and the lower bound could be static values since the aspect ratio Unity maintains always keeps the upper and lower bound of what a camera renders consistent.
With the aspect ratio (that you can get with camera.aspect or Screen.width / Screen.height), you can calculate the left and right borders.