如何跳过物理体(如平台)并落在它上面(SpriteKit)

时间:2015-04-13 16:20:44

标签: ios sprite-kit

我正在尝试使用像Mario / Sonic这样的Objective-C创建游戏。

现在它运作良好,但我仍然无法弄清楚当我的英雄站在它下面时可以让我的英雄跳过一个物理身体但是可以站在上面。

当heros位置高于平台并再次禁用时,我试图创建物理体。

1 个答案:

答案 0 :(得分:0)

这个问题的答案实际上并不太难,但对于你来说,实施一个完整的游戏对你来说会困难得多。对于新手程序员来说,这不是开始的。

首先是相同的代码项目(点击/点击屏幕跳转):

#import "GameScene.h"

typedef NS_OPTIONS(uint32_t, Level1PhysicsCategory) {
    CategoryPlayer  = 1 << 0,
    CategoryFloor0  = 1 << 1,
    CategoryFloor1  = 1 << 2,
};

@implementation GameScene {
    int playerFloorLevel;
    SKSpriteNode *node0;
    SKSpriteNode *node1;
    SKSpriteNode *node2;
}

-(void)didMoveToView:(SKView *)view {
    self.backgroundColor = [SKColor whiteColor];

    node0 = [SKSpriteNode spriteNodeWithColor:[SKColor grayColor] size:CGSizeMake(400, 10)];
    node0.position = CGPointMake(300, 200);
    node0.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node0.size];
    node0.physicsBody.dynamic = NO;
    node0.physicsBody.categoryBitMask = CategoryFloor0;
    node0.physicsBody.collisionBitMask = CategoryPlayer;
    [self addChild:node0];

    node1 = [SKSpriteNode spriteNodeWithColor:[SKColor grayColor] size:CGSizeMake(400, 10)];
    node1.position = CGPointMake(300, 300);
    node1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node1.size];
    node1.physicsBody.dynamic = NO;
    node1.physicsBody.categoryBitMask = CategoryFloor1;
    node1.physicsBody.collisionBitMask = CategoryPlayer;
    [self addChild:node1];

    node2 = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(50, 50)];
    node2.position = CGPointMake(300, 250);
    node2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node2.size];
    node2.physicsBody.categoryBitMask = CategoryPlayer;
    node2.physicsBody.collisionBitMask = CategoryFloor0;
    [self addChild:node2];

    playerFloorLevel = 0;
}

-(void)update:(CFTimeInterval)currentTime {
    if(((node2.position.y-25) > (node1.position.y+10)) && (playerFloorLevel == 0)) {
        node2.physicsBody.collisionBitMask = CategoryFloor0 | CategoryFloor1;
        playerFloorLevel = 1;
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
     for (UITouch *touch in touches) {
         CGPoint touchLocation = [touch locationInNode:self];
        //SKNode *node = [self nodeAtPoint:touchLocation];

        // change 75 value to 50 to see player jump half way up through floor 1
        [node2.physicsBody applyImpulse:CGVectorMake(0, 75)];
    }
}

代码的要点是玩家节点(node2)必须继续检查其相对于其他楼层的y位置(更新方法)。在该示例中,玩家跳过floor1。一旦玩家高于floor1,玩家节点的物理主体会修改其碰撞位掩码以包含floor1。

听起来很容易。但是,在真实游戏中,您将拥有大量的楼层,并且所有楼层的距离可能不均匀。编码时必须牢记所有这些。