[SKAction moveByX:100 y:50.0 duration:1.0]
[SKAction waitForDuration:1.0]
[SKAction moveByX:-100.0 y:-50 duration:1.0]];
[hull runAction:[SKAction repeatActionForever:hover];
return hull;}
- (SKSpriteNode *)newSpaceship
{
SKSpriteNode *hull= [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(64,32);
SKAction *hover= [SKAction sequence:@[
[SKAction waitForDuration:1.0]
[SKAction moveByX:100 y:50.0 duration:1.0]
[SKAction waitForDuration:1.0]
[SKAction moveByX:-100.0 y:-50 duration:1.0]];
[hull runAction:[SKAction repeatActionForever:hover];
return hull;}
此方法创建飞船的船体,并添加了一个简短的动画。需要注意的是引入了一种新的动作。一个重复的动作不断地重复的传递给它的动作。在这种情况下,序列一直重复。
现在构建并运行应用程序来看当前的行为,你应该看到一个矩形。
在建立复杂的有孩子的节点时,把用来在构造方法后面或者甚至是在子类中创建节点的代码分离出来,是一个很好的主意。这使得它更容易改变精灵的组成和行为,而无需改变使用精灵的客户端(client)。
3. 添加代码到newSpaceship方法来添加灯光。
[cpp]
SKSpriteNode *light1= [self newLight];
light1.position = CGPointMake(-28.0,6.0);
[hull addChild:light1];
SKSpriteNode *light2= [self newLight];
Light2.position = CGPointMake(28.0,6.0);
[hull addChild:light2];
SKSpriteNode *light1= [self newLight];
light1.position = CGPointMake(-28.0,6.0);
[hull addChild:light1];
SKSpriteNode *light2= [self newLight];
Light2.position = CGPointMake(28.0,6.0);
[hull addChild:light2];4. 实现newLight方法。
[cpp]
- (SKSpriteNode *)newLight
{
SKSpriteNode *light = [[SKSpriteNode alloc] initWithColor:[SKColor yellowColor] size:CGSizeMake(8,8)];
SKAction *blink= [SKAction sequence:@ [
[SKAction fadeOutWithDuration:0.25]
[SKAction fadeInWithDuration:0.25]];
SKAction * blinkForever = [SKAction repeatActionForever:blink];
[light runAction:blinkForever];
return light;
}
- (SKSpriteNode *)newLight
{
SKSpriteNode *light = [[SKSpriteNode alloc] initWithColor:[SKColor yellowColor] size:CGSizeMake(8,8)];
SKAction *blink= [SKAction sequence:@ [
[SKAction fadeOutWithDuration:0.25]
[SKAction fadeInWithDuration:0.25]];
SKAction * blinkForever = [SKAction repeatActionForever:blink];
[light runAction:blinkForever];
return light;
}当你运行应用程序时,你应该看到一对灯在飞船上。当飞船移动,灯光和它一起移动。这三个节点全都是连续动画。你可以添加额外的动作,让灯光在船的周围移动,它们总是相对船体移动。
创建能交互的节点
在实际的游戏中,你通常需要节点之间能交互。把行为添加给精灵的方法有很多,所以这个例子仅展示其中之一。你将添加新节点到场景,使用物理子系统模拟它们的运动并实现碰撞效果。
Sprite Kit提供了一个完整的物理模拟,你可以使用它添加自动行为到节点。也就是说,物理在使其移动的节点上自动模拟,而不是在节点上执行动作。当它与物理系统一部分的其他节点交互时,碰撞自动计算并执行。
添加物理模拟到飞船场景
1. 更改newSpaceship方法来添加一个物理体到飞船。
[cpp]
hull.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hull.size];
hull.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hull.size];
构建并运行应用程序。等一下!飞船垂直坠落到屏幕下方。这是因为重力施加到飞船的物理体。即使移动动作仍在运行,物理效果也被应用到飞船上。
2. 更改的newSpaceship方法来防止飞船受物理交互影响。
[cpp]
hull.physicsBody.dynamic = NO;
hull.physicsBody.dynamic = NO;当你现在运行它时,应用程序像之前那样运行。飞船不再受重力影响。稍后,这也意味着飞船的速度将不会受到碰撞的影响,。
3. 添加代码到createSceneContents方法来生成大量岩石。
[cpp]
SKAction * makeRocks = [SKAction sequence:@ [