【问题标题】:Creating a dynamically sized SKSpriteNode platform for endless runner game为无尽的跑步游戏创建动态大小的 SKSpriteNode 平台
【发布时间】:2015-11-08 11:25:53
【问题描述】:

我正在为 IOS 创建我的第一个 Endless Runner 游戏,我希望它尽可能动态。我想创建一个大型“平台”图像,然后使用该图像创建各种大小的平台。

这个想法是随机选择一个数字作为平台的宽度,然后生成与所选尺寸相匹配的精灵和主体。完成此操作后,仅使用图像的一部分将图像填充到精灵中。

目前我正在使用以下内容,但这会根据 UIImage 的大小创建节点。

SKSpriteNode *spritePlatform = [[Platform alloc] initWithImageNamed:@"Platform"];

[spritePlatform setPosition:CGPointMake(self.frame.size.width + (spritePlatform.frame.size.width / 2), 200)];

spritePlatform.name = @"Platform";

spritePlatform.physicsBody = [SKPhysicsBody bodyWithTexture:spritePlatform.texture size:CGSizeMake(300, 40)];
spritePlatform.physicsBody.affectedByGravity = NO;
spritePlatform.physicsBody.dynamic = NO;

// 1
spritePlatform.physicsBody.usesPreciseCollisionDetection = YES;
// 2
spritePlatform.physicsBody.categoryBitMask = CollisionCategoryPlatform;

spritePlatform.physicsBody.contactTestBitMask = CollisionCategoryPlayer;


[self addChild:spritePlatform];
[self movePlatform:spritePlatform];

所以理想情况下我想

  1. 根据随机宽度和固定高度创建精灵。
  2. 使用较大图像的一部分来填充精灵。

有什么想法可以做到这一点吗?

谢谢

【问题讨论】:

    标签: ios objective-c sprite-kit skspritenode


    【解决方案1】:

    根据随机宽度和固定高度创建精灵。

    width 选择一个随机数很简单。您可以使用arc4random_uniform 并确保选择合理范围内的数字(小于您的平台图像)。

    使用较大图像的一部分来填充精灵。

    这可以通过使用textureWithRect:inTexture: 来完成。第一个参数是单位坐标空间中的一个矩形,它指定要使用的纹理部分。第二个参数是创建新纹理的整个平台纹理。

    以下是有关如何设置每个平台的大小/部分的提示:

    1. (0, 0)是整个平台坐标的左下角。

    2. x/y 坐标的范围是 0 到 1,不是平台图像的真实尺寸。

    给定一个由平台图像platformAllTexture创建的纹理和一个随机的width在第一步中,平台纹理可能是:

    // Fixed height is set as half of the platform image
    SKTexture *platformTexture = [SKTexture textureWithRect:CGRectMake(0, 0, width/platformAllTexture.size.width, 1/2.0)          
                                                  inTexture:platformAllTexture];
    

    这样,您就获得了动态大小平台的纹理platformTexture

    在上面的例子中,如果矩形定义为CGRectMake(0, 0, 1/3.0, 1/2.0),你会得到类似的结果:

    【讨论】:

    • 我会试一试,看看效果如何。感谢您提供信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2016-03-25
    • 2012-11-15
    • 1970-01-01
    相关资源
    最近更新 更多