I am trying to create a game in Spritekit. I got 2 objectives, with no body, the sun and the moon. At first the sun should spawn on the right corner of the screen, moving to the left. If the sun is out of the screen, for e.g. at x = -30, the moon should appear at the right corner of the screen.
Also, I want to change the background color. I got no Images, so I am using RGB for it. For e.g., if the Sun hits the point x = 50, the background color should go darker and darker until the moon appears. I use SkyBlue = 135,206,250.
My Code doesn't work, the sun moves to the left, but the moon don't appear.
-(void)Background{
Sun = [SKSpriteNode spriteNodeWithImageNamed:@"Sun.png"];
Sun.size = CGSizeMake(60, 60);
Sun.position = CGPointMake(360, 500);
SKAction * MoveLeft = [SKAction moveByX:-400 y:0 duration:15];
[Sun runAction:MoveLeft];
[self addChild:Sun];
Moon = [SKSpriteNode spriteNodeWithImageNamed:@"Moon.png"];
Moon.size = CGSizeMake(60, 60);
Moon.position = CGPointMake(360, 500);
if (Sun.position.x < 60) {
[Moon runAction:MoveLeft];
}
[self addChild:Moon];
}
Your method is only being called once, and so :
if (Sun.position.x < 60) {
[Moon runAction:MoveLeft];
}
Is only called once.
Solution:
Override the update function on your scene (this is run at every frame update):
-(void)update:(NSTimeInterval)currentTime {
if (Sun.position.x < 60 && Sun!=nil) {
Moon = [SKSpriteNode spriteNodeWithImageNamed:@"Moon.png"];
Moon.size = CGSizeMake(60, 60);
Moon.position = CGPointMake(360, 500);
[Moon runAction:MoveLeft];
[self addChild:Moon];
Sun = nil;
[Sun removeFromParent]; // Make sure that this code isn't called again
}
}