# Understanding vector2 set in Libgdx

I am trying to understand why in the following code the programmer user vector2.set() ?

//create enemies
enemyTimer -= delta;
if (enemyTimer < 0) {
enemyTimer = ENEMY_DELAY;

Enemy enemy = new Enemy();
vector2.set(camera.viewportWidth / 2, camera.viewportHeight / 2); //this does not make sense to me
vector2.rotate(MathUtils.random(360f));
enemy.x = vector2.x;
enemy.y = vector2.y;
}


According to the Libgdx javadoc, vector2.set() sets the components of the vector. By 'components' I understand direction and magnitude.

Now, I see the that each enemy starts at (0,0) and points to the center of the viewport. I also understand that the programmer will most likely move the camera around and therefore the next enemy will start not at (0,0) but some other location within the viewport. So, based on this setup will the enemies all go to the center of the viewport?

Let's suppose we're working in screen pixels, and our viewport is a 1920x1080 screen. (The same logic holds in other coordinate systems too, but the exact numbers may differ)

vector2.set(camera.viewportWidth / 2, camera.viewportHeight / 2);


This sets the vector to (1920/2, 1080/2) which is (980, 540). You can think of this as the offset from the center of the screen to one corner.

vector2.rotate(MathUtils.random(360f));


This rotates that vector by a random angle from 0 to 360 degrees, preserving its length. So it's still as long as half the diagonal of the screen, but now pointing in a random direction.

vector2.add(camera.position.x, camera.position.y);


This adds this random offset to the camera's position. That gives us a resulting point somewhere on a circle centered on the camera, with radius equal to half the screen's diagonal.

enemy.x = vector2.x;
enemy.y = vector2.y;


This positions the newly-spawned enemy at that point.

So what this is doing is spawning an enemy at some random point just at/outside the current camera view - either right at the corner of the screen, or somewhere equally far away in another direction.

Doing it this way, enemies take the same amount of time to reach the player / the player takes the same amount of time to reach them, no matter which random direction they spawned in. That fixes a potential problem where enemies spawning on the right side of the screen have more time to ready an attack than enemies spawning from the top (or vice versa on a portrait display)

• Thanks @LudoProf . Ok so each enemy is sitting right outsisde the camera! How can we use this Vector2 to move the enemy. Is it possible to cache the vector2 and move the enemy following the direction of the vector2.
– i_o
Commented May 1 at 16:42
• That sounds like a different question, which would require seeing more of the code. If this is for a homework assignment, you should also document that in your question post, so folks know how to focus on helping you learn the lesson. Commented May 1 at 16:54