启动Xcode和选择新的项目文件从主菜单。选择iOS \应用\ SpriteKit游戏模板并单击“下一步”。
输入你的游戏名称品名,选择iPhone设备运行一下:
SpriteKit物理和碰撞检测
SpriteKit带有一个物理引擎内置的,可以模拟真实的运动和碰撞检测。我们打算用SpriteKit的物理引擎将我们的飞船,飞船和导弹之间的碰撞检测。我们将在下面的步骤中建立我们的游戏:
1、加入游戏的主要角色(飞船)在屏幕上(1)
2、添加滚动的背景(1)
3、增加一个导弹,宇宙飞船可以碰撞(2)
4、显示游戏结束屏幕时,飞船和导弹给重放选项碰撞(2)
添加的主要特征
#import "MyScene.h"
@implementation MyScene{
SKSpriteNode *ship;
SKAction *actionMoveUp;
SKAction *actionMoveDown;
}
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.backgroundColor = [SKColor whiteColor];
//Making self delegate of physics World
self.physicsWorld.gravity = CGVectorMake(0,0);
self.physicsWorld.contactDelegate = self;
}
return self;
}
@end
添加 飞船和刚体:
-(void)addShip{
//initalizing spaceship node
SKSpriteNode * ship = [SKSpriteNode new];
ship = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
[ship setScale:0.5]; ship.zRotation = - M_PI / 2;
//Adding SpriteKit physicsBody for collision detection
ship.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ship.size];
ship.physicsBody.categoryBitMask = shipCategory;
ship.physicsBody.dynamic = YES;
ship.physicsBody.contactTestBitMask = obstacleCategory;
ship.physicsBody.collisionBitMask = 0;
ship.name = @"ship";
ship.position = CGPointMake(120,160);
[self addChild:ship];
actionMoveUp = [SKAction moveByX:0 y:30 duration:.2];
actionMoveDown = [SKAction moveByX:0 y:-30 duration:.2];
}
背景滚动
- (void)initalizingScrollingBackground
{
for (int i = 0; i < 2;i++) {
SKSpriteNode *bg = [SKSpriteNode spriteNodeWithImageNamed:@"bg"];
bg.position = CGPointMake(i *bg.size.width, 0);
bg.anchorPoint = CGPointZero;
bg.name = @"bg";
[self addChild:bg];
}
设置障碍物
// moveObstacle [ˈɑbstək(ə)l] 障碍物
- (void)moveObstacle
{
NSArray *nodes = self.children;
for (SKNode *node in nodes) {
if (![node.name isEqual:@"bg"]&& ![node.name isEqual:@"ship"]) {
SKSpriteNode *ob = (SKSpriteNode *) node;
CGPoint obVelocity = CGPointMake(-OBJECT_VELOCITY, 0);
CGPoint amtToMove = CGPointMultiplyScalar(obVelocity, _dt);
ob.position = CGPointAdd(ob.position, amtToMove);
if (ob.position.x < -100) {
// 移除父节点
[ob removeFromParent];
}
}
}
}
定时器更新:
- (void)update:(CFTimeInterval)currentTime
{
if (_lastUpdateTime) {
_dt = currentTime - _lastUpdateTime;
} else {
_dt = 0;
}
_lastUpdateTime = currentTime;
if (currentTime - _lastMissileAdded >1) {
_lastMissileAdded = currentTime + 1;
// 添加导弹
[self addMissile];
}
// 移除背景
[self moveBg];
// 移除障碍物
[self moveObstacle];
}