# Handling Enemy Movement Within Camera View

I’m working on a game where I spawn the enemies just outside the camera view. At first I thought that having a Random.Range set would do the trick for moving them into camera view at a random distance but I noticed that if the max number is to high then it will move out of scene view and if it’s to low it they would all be at a same distance. How can I make it so that I can spawn my enemies and allow them to move randomly across the scene within camera view?

P.S it a 2D game set on Orthographic

Edit:

“I’m pretty sure I’m envisioning to well in my mind I forgotten detail sorry. But let’s put it this way, I got about maybe 20+ spawn points just setup just right outside the camera view. My script would randomly select one of those points and spawn an enemy. The enemy then moves an X amount of distance based on my min and max number which are set maybe 1 - 20 (so it travel a 1 - 20 distance) across the screen into view. My problem is that the width of the screen is different and so is the height so if it spawns at the bottom of the screen and travels 20 distance up it will then leave the camera view but if it spawn on the left the 20 distance traveled will keep it inside the camera view. Hopefully this make more sense ><”

OK, so I sort of understand. Right now I’m envisioning say an Asteroids type game, where maybe you spawn rocks outside and have it move towards the camera view yes?

IF this is the case, then you want to just apply a force to the objects, rather than move them randomly. For example:

``````GameObject asteroid;

float zDistanceFromCamera = 10.0f;

Vector3 vScreenMidPoint = Camera.main.ViewportToWorldPoint(0.5f,0.5f,zDistanceFromCamera);

Vector3 distanceToMidpoint = asteroid.transform.position - vScreenMidPoint;

Vector3 normalizedV = distanceToMidpoint.Normalize;

asteroid.rigidbody.AddForce(iImpulse * normalizedV);
``````

(it’s in C#, and untested btw) - but basically if Asteroid is your game object and you want to move it into view, i set a direction for it’s movement (this always just moves towards the center of the viewport, if your 2d game is in a 3d world, then it moves toward the midpoint at a depth of zDistanceFromCamera.

You can easily change this to randomize where in view the asteroid will go, it can go towards any of the 4 corners or in between by changing:

``````  Vector3 vScreenMidPoint = Camera.main.ViewportToWorldPoint(0.5f,0.5f,zDistanceFromCamera);//change this

///--- To this:

Vector3 vViewportPoint = Camera.main.ViewportToWorldPoint(Random.Range(0,1),Random.Range(0,1),zDistanceFromCamera);

//well, also i changed the variable name to illustrate it's not the midpoint any longer...
``````