Overview: I'm adding an enemy from the top of the scene. The enemy is initially moving right with 150 velocityX. The map has a left wall and a right wall. When then enemy his the right and left wall he should immediately reverse direction.
Problem: When I call the function spawnEnemy from initWithSize the enemy behaves as expected by reversing direction when the enemy hits each wall. When I use an NSTimer to call spawnEnemy every 2 seconds the SKScene does not recognize that the enemy makes contact with the wall and doesn't reverse the enemies direction. The code is provided below.
SPAWN ENEMY METHOD:
-(void)spawnEnemy{
self.testingEnemy = [SKSpriteNode spriteNodeWithImageNamed:@"normalEnemy.png"];
self.testingEnemy.position = (CGPoint) {
CGRectGetMidX(self.scene.frame),
300
};
self.testingEnemy.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.testingEnemy.frame.size];
self.testingEnemy.physicsBody.dynamic = TRUE;
self.testingEnemy.physicsBody.affectedByGravity = TRUE;
self.testingEnemy.physicsBody.mass = 0.00150;
self.testingEnemy.physicsBody.restitution = 0.0;
self.testingEnemy.physicsBody.allowsRotation = FALSE;
self.testingEnemy.physicsBody.linearDamping = 0.0;
[self addChild:self.testingEnemy];
}
initWithSize
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
//[self spawnEnemy]; <--- This works with expected behavior
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(spawnEnemy) userInfo:nil repeats:NO];
}
return self
}
didBeginContact
- (void)didBeginContact:(SKPhysicsContact *)contact
{
if (contact.bodyA == self.testingEnemy.physicsBody && contact.bodyB == [self.map rightWall].physicsBody) {
NSLog(@"Hit right wall");
normalEnemyVelocityX = -normalEnemyVelocityX;
}
}
Here is a link to the project file: