我一直在寻找有关Objective C或spriteKit的空间散列的教程。我已经找到了其他语言的例子,但我似乎无法弄明白。我已经走到了这一步,但我被卡住了。
这将Enemy Sprites加载到NSMutableDictionary,我将它们的x,y位置除以64得到它们的cellID(我使用cellID作为NSMutableDictionary中敌人的关键字)。
- (void)loadEnemies {
TMXObjectGroup *enemiesGroup = [self.map groupNamed:@"enemies"];
for (NSDictionary *enemyDict in enemiesGroup.objects) {
NSString *enemyType = enemyDict[@"type"];
NSString *firstFrameName =
[NSString stringWithFormat:@"%@1.png",enemyType];
CGPoint enemyPosition =
CGPointMake([enemyDict[@"x"] floatValue], [enemyDict[@"y"] floatValue]);
CGPoint cellNumber =
CGPointMake(enemyPosition.x / 64, enemyPosition.y / 64);
NSString *CellID =
[NSString stringWithFormat:@"%@",NSStringFromCGPoint(cellNumber)];
SMCEnemy *enemy = [[NSClassFromString(enemyType)alloc]
initEnemyWithImageNamed:firstFrameName Position:enemyPosition];
enemy.position = enemyPosition;
enemy.player = self.cat;
enemy.map = self.map;
enemy.delegate = self;
[self.map addChild:enemy];
enemy.zPosition = 900;
//enemies added to NSMutableDictionary
[self.enemeyDictionary setObject:enemy forKey:CellID];
}
}
我已经使用CellID作为键将敌人添加到NSMutableDictionary中。
此检查与玩家的碰撞,我首先检查玩家与每个敌人之间的距离;如果距离小于1000,那么敌人就会变得活跃。
- (void)checkForEnemyCollisions:(SMCEnemy *)enemy {
CGFloat distance = CGPointDistance(enemy.posiiton, self.player.position);
if (distance < 1000){
enemy.isActive = YES;
} else {
enemy.isActive = NO;
}
if (enemy.isActive && enemy.life > 0) {
//cat hurt
if ((CGRectIntersectsRect(self.cat.collisionBoundingBox, enemy.collisionBoundingBox) || CGRectIntersectsRect(self.cat.collisionBoundingBox, enemy.attackBox)) && self.cat.isActive && !enemy.hidden && enemy.canHurtPlayer){
enemy.attackBox = CGRectNull;
if (enemy.position.x < self.cat.position.x) {
[self.cat bounceWithDirection:1];
}else{
[self.cat bounceWithDirection:-1];
}
[self.cat tookHit:self.cat];
[self movementCoolDownForCharacter:self.cat coolDownTime:.5];
}
// enemy hurt
if (CGRectIntersectsRect(enemy.collisionBoundingBox, self.cat.attackBox)&& !enemy.isHurt && enemy.isStun && !enemy.hidden) {
CGRect intersection = CGRectIntersection(enemy.collisionBoundingBox,self.cat.attackBox);
_hit.position = CGPointMake(intersection.origin.x, intersection.origin.y);
_hit.hidden = NO;
SKAction *DoneAction = [SKAction runBlock:(dispatch_block_t)^() {
_hit.hidden = YES;
}];
SKAction *moveLaserActionWithDone = [SKAction sequence:@[enemy.hitAnim,DoneAction]];
[_hit runAction:moveLaserActionWithDone];
enemy.isHurt = YES;
[enemy tookHit:self.cat];
[self movementCoolDownForCharacter:enemy coolDownTime:.5];
}
}
更新方法
- (void)update:(NSTimeInterval)currentTime {
NSTimeInterval delta = currentTime - self.previousUpdateTime;
self.previousUpdateTime = currentTime;
if (delta > 0.1) {
delta = 0.1;
}
for (SMCEnemy *enemy in self.enemies) {
[self checkForEnemyCollisions:enemy];
}
}
我想使用空间哈希而不是通过敌人阵列中的每个敌人物品来提高性能。
我卡住任何帮助真的很棒! :d