I need a bit of math help for my game.
I'm using Javascript and the Canvas tag to create a circular world, think God Finger, and Reus. The current version of my game is here: http://lazyeels-sandbox.appspot.com/
The problem:
The Canvas draws an arc (or circle) starting at 90 degrees going clockwise. See an example image.
My game splits the world in to segments (tiles). The world is 10 tiles in length I would like to calculate which tile the mouse is hovering over so the player can add buildings or adjust the height of the tile.
So I need to calculate the offset and deduct it from the mouse angle (either radians or degrees is fine). However, I can't seem to get it right. I know that in theory I should do the following:
- Calculate the angle of the mouse.
- Calculate the tile by dividing by the segment size (as per regular tile maps i.e. y-axis/tilewidth).
- Remove the offset of the angle to point 0 degrees at the top of the circle rather than 90 degrees clockwise).
- Deduct the offset to get the new tile position.
Here is the main function I'm using;
var getMouseAngle = function(mouse){
var world_length = 10;
var segment = (Math.PI * 2)/world_length;
// Get the distance
var dx = mouse.x - ((canvas.width * 0.5) - Game.camera.xScroll);
var dy = mouse.y - ((canvas.height - Game.camera.yScroll) * Game.camera.zoom);
// calculate the angle
var arctan = Math.atan2(dy, dx);
// Reset the angle if it is a negative value
var angle = dy < 0 ? (Math.PI * 2) + arctan: arctan; // perhaps this is where I need to apply the offset.
// Calculate the tile
var orig_tile = angle/segment;
// Calculate the offset
var offset_tile = ((Math.PI * 3/2)/segment); // calculate offset clockwise = 270 degrees to the top of the circle (where the player sits).
var tile = (orig_tile - offset_tile) // This is soooooo wrong
return {
dx: dx,
dy: dy,
degrees: (angle * 180/Math.PI).toFixed(2),
radian: angle.toFixed(2)
tile: Math.floor(tile),
};
By comparison the player tile function was way easier:
Player.getTile = function(rotation){
var tile = Math.floor(rotation/Game.level.segment);
if(rotation > 0){
tile = Math.abs((Game.level.world.length - tile)-1);
} else {
tile = Math.abs(tile)-1;
}
if(rotation == 0){
tile = 0;
}
return tile;
};
Does anyone know where I'm going wrong in the calculation, i.e. how and when should I apply the offset - on the angle before calculating the tile, or afterwards?
I haven't shown the other permutations I tried, such as deducting the offset from the original angle, all of these resulted in the wrong tile ID being returned.
I know it should be a similar process to the player function, i.e. using the word_length in the calculation.
y
multiplied by zoom? \$\endgroup\$