Search code examples
iosxcodeswifttiledjstilemap

How to get nearest tile from touch with JSTileMap swift


I have just made a function that creates an object at the user's touch location but I want it to be auto aligned with the center of the tiles according to my tiled map.

Right now, I'm only able to place objects at my touch location instead of auto redirecting it to the nearest tile.

http://puu.sh/ggxOG/2785a2eeca.png (This is how my tiles look like 32x32)

JSTileMap functions

@class JSTileMap;

@interface TMXLayer : SKNode
@property (strong, nonatomic) TMXLayerInfo* layerInfo;
@property (strong, nonatomic) NSMutableSet* tileInfo;  // contains TMXTilesetInfo objects
@property (assign, nonatomic) CGSize mapTileSize;

/** Returns the width of the layer (layerGridSize.width * mapTileSize.width) */
@property (readonly,nonatomic) CGFloat layerWidth;

/** Returns the height of the layer (layerGridSize.height * mapTileSize.height) */
@property (readonly,nonatomic) CGFloat layerHeight;

/** Returns the JSTileMap that contains this layer */
@property (weak, nonatomic) JSTileMap* map;

- (CGPoint)pointForCoord:(CGPoint)coord;
- (CGPoint)coordForPoint:(CGPoint)point;

- (void)removeTileAtCoord:(CGPoint)coord;
- (SKSpriteNode*)tileAt:(CGPoint)point;
- (SKSpriteNode*)tileAtCoord:(CGPoint)coord;
- (int)tileGidAt:(CGPoint)point;
- (id)propertyWithName:(NSString*)name;
- (NSDictionary*)properties;

@end

Solution

  • I solved this this way to get the nearest tile.

    var layer: TMXLayer = map.layerNamed("World1") // retrieve layer from tiled map
    if let object = layer.tileAt(location) { // if there is a sprite(tile) at that position then set it as a var
    position = object.position // update position var to the position of the sprite
    }