Friday, December 13, 2019

algorithm - Finding out which tile a mouse click landed in


I am working on an isometric grid based game and im having an issue trying to link a mouse click from the user to a tile. I have been able to split the problem into 2 parts :



  • Finding a rectangle that surrounds a tile (which I have been able to do)

  • Figuring out from the rectangle which tile the click landed in (has got me stumped)


Here is an example of a rectangle with tiles on the inside:


Rectangle containing tiles


The rectangle is 70px long and 30px high so if i use an input of say 30x(top)/20y(left) how would I go about determining which tile this fell into?



Answer




For each step you make in x direction you will move 35px left and -15px up to your canvas;


For each step you make in y direction you will move -35px left and -15px up to your canvas;


tile to cartesian


This means that you can convert your tile coordinate system easely in pixel:


(x,y) => (35·x,-15·x) + (-35·y, -15·y) = (35·x - 35·y, -15·x - 15·y) = (Xpx,Ypx)


You have to resolve the inverse problem you know Xpx and Ypx and you want to know x and y (in tile coordinate).


Xpx = 35·x - 35·y ;


Ypx = -15·x - 15·y ;


can you solve this?it should be:


x = 1/70·Xpx - 1/30·Ypx



y = -1/70·Xpx - 1/30·Ypx


Obviously you will have non integer values in general case: taking the ceil of both x and y will gives you the coordinate of the whole tile.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...