slycrel / JSTileMap

TMX Map viewer for SpriteKit
Other
212 stars 34 forks source link

Detect collisions with objects #9

Closed ChrisBuchholz closed 10 years ago

ChrisBuchholz commented 10 years ago

Perhaps it's already implemented, but I fail to see a way to detect collisions with objects, like you do with tiles.

For detecting collisions with tiles in a particular tile layer, I run this snippet of code from my -(void)update:(NSTimeInterval)currentTime method

NSInteger indices[8] = {7, 1, 3, 5, 0, 2, 6, 8};

for (NSUInteger i = 0; i < 8; i++) {
    NSInteger tileIndex = indices[i];

    CGRect playerRect = [player collisionBoundingBox];
    CGPoint playerCoord = [myTileLayer coordForPoint:player.desiredPosition];

    NSInteger tileColumn = tileIndex % 3;
    NSInteger tileRow = tileIndex / 3;
    CGPoint tileCoord = CGPointMake(playerCoord.x + (tileColumn - 1), playerCoord.y + (tileRow - 1));

    NSInteger gid = [self tileGIDAtTileCoord:tileCoord forLayer:myTileLayer];
    if (gid != 0) {
        CGRect tileRect = [self tileRectFromTileCoords:tileCoord];

        if (CGRectIntersectsRect(playerRect, tileRect)) {
            NSLog(@"collision with tile detected");
        }
    }
}

This doesn't work using an object layer instead of a tile layer.

Is there a proper way to detect collisions with objects? If not, I should give it a go at implementing it!

slycrel commented 10 years ago

Hi @ChrisBuchholz. There is not currently any way to directly get at the tile objects in the way you are proposing. I'll add it to my list of things to do. In the meantime, let me know if you get it taken care of.

slycrel commented 10 years ago

Also note that with issue #12 I've added the name to tile objects, so you can get at the sprite of a given object much easier.

slycrel commented 10 years ago

@ChrisBuchholz did the solution for Issue #12 take care of this for you?

ChrisBuchholz commented 10 years ago

Yes, it got me through the problem anyways. Thanks for the tip!