Wednesday, December 11, 2019

cocos2d iphone - How do I convert the coordinates of a click to a tilemap position?


How do you turn a tilemap (produced by TileD) for cocos2d where I can click on individual items and get a callback?


Is it just a case of converting captured touch and finding out where it is on the tilemap and then converting that to pixels -- but that doesn't say what item was clicked on.



I have a tilemap of a city with buildings on it, and I'd like to be able to click or press on a specific building, get a callback.


What would be the best way to accomplish this?



Answer



I think you're getting your pixel coordinates and tilemap coordinates confused.


Tile coordinates count tiles.


tile coordinates


Pixel coordinates count pixels.


pixel coordinates


To convert from a pixel coordinate to a tile coordinate, divide the click_x by the tile width and the click_y by the and tile height, to get the tile coordinates x and y. (Discard the remainders to get an integer.)


The reason this works is pretty clear if we overlay the two coordinate systems:



How the solution works


In this above case, the pixel coordinates of the click would correspond to 6,4 in tile coordinates.


Once you know what tile position a click corresponds to, it should be trivial to find the contents of that 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...