首页 文章

XCode SpriteKit物理体与精灵大小不匹配

提问于
浏览
1

我是精灵套件的新手并且发展我的技能我正在创造一个类似于流行的Flappy Bird的游戏 . 我已经创建了一种方法,可以将管道添加到场景中作为障碍物 . 我通过使用bodyWithRectangleOfSize并将其设置为obstacle.size为这些障碍创建了静态物理实体 . 然而,物理主体的大小与屏幕上显示的管道图像的大小不同 . 什么在屏幕上显示为空白空间,鸟儿撞到了 . 这只鸟也可以飞过管道的各个部分 . 这似乎是由物理机构引起的,包括障碍物在大小上的位置 . (例如,管道在屏幕底部上方浮动320px,高度为240px . 物理主体伸展到整个屏幕长度 . )

更新:这不再是问题 . 我现在发现底部的物理体是短的和胖的,而顶部的物理体太长了 . 差距在那里,但它位于显示管道的中间 .

正如我之前所说 . 我是spritekit的新手,这很可能是我的一个基本错误 . 任何帮助表示赞赏 . 谢谢 .

以下是我生成每个障碍的代码:

-(void)initialiseObstacles:(int)position
{

//create random height

int random = (arc4random()%250) + 150;



    //add bottom pipe and physics body

    SKSpriteNode *lowObstacle = [SKSpriteNode     spriteNodeWithImageNamed:@"pipe.png"];
    lowObstacle.size = CGSizeMake(50, random);
    lowObstacle.position = CGPointMake(position + 200, 0);
    lowObstacle.anchorPoint = CGPointMake(0,0);
    lowObstacle.name = @"lowObstacle";

    [self addChild:lowObstacle];

    lowObstacle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:lowObstacle.frame.size];
    lowObstacle.physicsBody.dynamic = NO;
    lowObstacle.physicsBody.categoryBitMask = obstacleCategory;

    //add top pipe & physics body

    SKSpriteNode *highObstacle = [SKSpriteNode spriteNodeWithImageNamed:@"pipetop.png"];
    highObstacle.anchorPoint = CGPointMake(0,0);
    highObstacle.size = CGSizeMake(50, 430-lowObstacle.size.height);
    highObstacle.position = CGPointMake(lowObstacle.position.x,lowObstacle.size.height + 130);
    highObstacle.name = @"highObstacle";

    [self addChild:highObstacle];

    highObstacle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:highObstacle.frame.size];
    highObstacle.physicsBody.dynamic = NO;
    highObstacle.physicsBody.categoryBitMask = obstacleCategory;

}

此代码每100帧生成一个管道,并由更新调用:

-(void)spawn{


frames = frames + 1;

if (frames == 100) {

    [self initialiseObstacles:200];
    frames = 0;
    }
}

此代码移动管道:

-(void)moveObstacles
{
[self enumerateChildNodesWithName:@"lowObstacle" usingBlock:^(SKNode *node, BOOL *stop) {
SKSpriteNode *ob = (SKSpriteNode *)node;
ob.position = CGPointMake(ob.position.x - 1.5, 0);


if (ob.position.x < -ob.size.width) {
    [ob removeFromParent];
}
}];

[self enumerateChildNodesWithName:@"highObstacle" usingBlock:^(SKNode     *node, BOOL *stop) {
    SKSpriteNode *highOb = (SKSpriteNode *)node;
    highOb.position = CGPointMake(highOb.position.x - 1.5, highOb.position.y);

    if (highOb.position.x < - highOb.size.width) {
        [highOb removeFromParent];

    }
}];
}

1 回答

  • 0

    使用图像初始化时,应保留lowobstacle.size . 当你设置物理体时

    bodywithrectangleofsize:lowobstacle.frame.size

    应该是bodywithrectangleofsize:lowobstacle.size

    我设置锚点的经验并不好 . 它似乎摒弃了物理机构 . 祝好运!

相关问题