I've been attempting to display the positions of players in a 3D game, on a web page, from an overhead view perspective (like a minimap). I'm simply superimposing markers (via SVG) on a 1024x1024 image of the game's level (an overhead view, taken from the game itself). I'm only concerned with the x
, y
coordinates, since I'm not using z
in an overhead view.
The game's world has equal min/max coordinates for both x
and y
: -4096
to 4096
. The 0, 0
coordinate is the center of the world.
To make things even more interesting, the initial position of a game level, within the game world, is arbitrary. So, for example, the upper-left world coordinate for the particular level I've been testing with is -2440, 3383
.
My initial confusion comes from the fact that the 0,0
coordinate in a web page is the top-left, versus center in the world space.
How do I correctly convert the 3D world space coordinates to properly display in a web page viewport of any dimension?
Here's what I've tried (I've been attempting to use the viewbox attribute in svg to handle the upper left world coordinate offset)
scalePosition: function (targetWidth, targetHeight) {
// in-game positions
var gamePosition = this.get('pos');
var MAX_X = 8192,
MAX_Y = 8192;
// Flip y
gamePosition.y = -gamePosition.y;
// Ensure game coordinates are only positive values
// In game = -4096 < x|y < 4096 (0,0 = center)
// Browser = 0 < x|y < 8192 (0,0 = top-left)
gamePosition.x += 4096;
gamePosition.y += 4096;
// Target dimenions
targetWidth = (targetWidth || 1024),
targetHeight = (targetHeight || 1024);
// Find scale between game dimensions and target dimensions
var xScale = MAX_X / targetWidth,
yScale = MAX_Y / targetHeight;
// Convert in-game coords to target coords
var targetX = gamePosition.x / xScale,
targetY = gamePosition.y / yScale;
return {
x: targetX,
y: targetY
};
},