Below are some useful vector functions we have written during the years and wanted to share. Enjoy!
Convert World Coordinates to Screen Coordinates
/**
* WolrdToScreen
* Converts XY world coordinates to screen coordinates
* @param x - X world coordinate
* @param y - Y world coordinate
* @param camera - camera
* @return Vector2
*/
public Vector2 WorldToScreen(float x, float y, Camera camera)
{
Vector3 coords = new Vector3(x, y, 0);
camera.project(coords);
Vector2 resultPos = new Vector2(coords.x, coords.y);
return resultPos;
}
Convert World Coordinates to Screen Coordinates and center provided texture
/**
* WorldToScreen
* Converts XY world coordinates to screen coordinates and centers texture
* @param x - X world coordinate
* @param y - Y world coordinate
* @param Texture - texture to center
* @param divide - divide texture by 2
* @param camera - camera
* @return Vector2
*/
public Vector2 WorldToScreen(float x, float y, Texture texture, boolean divide, Camera camera)
{
Vector3 coords = new Vector3(x, y, 0);
camera.project(coords);
if(divide)
{
coords.x = coords.x - (texture.getWidth()/2);
coords.y = coords.y - (texture.getHeight()/2);
}
else
{
coords.x = coords.x - texture.getWidth();
coords.y = coords.y - texture.getHeight();
}
Vector2 resultPos = new Vector2(coords.x, coords.y);
return resultPos;
}
Convert Screen Coordinates to World Coordinates.
/**
* ScreenToWorld
* Converts XY screen coordinates to world coordinates
* @param x - X screen coordinate
* @param y - Y screen coordinate
* @param camera - Camera object
* @return Vector2
*/
public Vector2 ScreenToWorld(float x, float y, Camera camera)
{
Vector3 coords = new Vector3(x, y, 0);
camera.unproject(coords);
Vector2 resultPos = new Vector2(coords.x, coords.y);
return resultPos;
}
Calculate the angle between two vectors.
/**
* AngleBetweenVectors
* Determines the angle between two vectors
* @param origin - First coordinates
* @param target - Second coordinates
* @return
*/
public static double AngleBetweenVectors(Vector2 origin, Vector2 target) {
double angle = Math.atan2(target.y - origin.y, target.x - origin.x);
return angle;
}

Leave A Comment