Friday, May 17, 2024
HomeGame DevelopmentUnderstanding vector2 set in Libgdx

Understanding vector2 set in Libgdx


Let’s suppose we’re working in screen pixels, and our viewport is a 1920×1080 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)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments