我试图在迷宫中实现物体的随机移动,所以我用可碰撞的墙壁制作了瓷砖地图。我正在使用这样的代码检查对象可以移动的每个方向的碰撞:
int directionsCount = 4;
CGPoint position = sprite.position;
CCArray *newPositions = [CCArray arrayWithCapacity:directionsCount];
CGFloat tileSize = _tileMap.tileSize.width;
[newPositions addObject:[NSValue valueWithCGPoint:CGPointMake(position.x, position.y + tileSize)]];
[newPositions addObject:[NSValue valueWithCGPoint:CGPointMake(position.x + tileSize, position.y)]];
[newPositions addObject:[NSValue valueWithCGPoint:CGPointMake(position.x, position.y - tileSize)]];
[newPositions addObject:[NSValue valueWithCGPoint:CGPointMake(position.x - tileSize, position.y)]];
for (NSValue *value in newPositions) {
int tileGid = [_meta tileGIDAt:[self tileCoordForPosition:[value CGPointValue]]];
if (tileGid) {
NSDictionary *properties = [_tileMap propertiesForGID:tileGid];
if (properties) {
NSString *collision = [properties valueForKey:@"Collidable"];
if (collision && [collision compare:@"True"] == NSOrderedSame) {
[newPositions removeObject:value];
}
}
}
}
[sprite runAction:[CCMoveTo actionWithDuration:1.0f position:[[newPositions objectAtIndex:(CCRANDOM_0_1() * [newPositions count])] CGPointValue]]];
但在少数情况下,当有死胡同或路径从正确的物体转向穿过墙壁时。有没有办法解决这样的环境?谢谢。