OGeek|极客世界-中国程序员成长平台

标题: ios - 为无尽的运行游戏创建动态大小的 SKSpriteNode 平台 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 09:43
标题: ios - 为无尽的运行游戏创建动态大小的 SKSpriteNode 平台

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

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

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

SKSpriteNode *spritePlatform = [[Platform alloc] initWithImageNamed"latform"];

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

spritePlatform.name = @"latform";

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. 根据随机宽度和固定高度创建 Sprite 。
  2. 使用较大图像的一部分来填充 Sprite 。

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

谢谢



Best Answer-推荐答案


Create a sprite based upon a random width and fixed height.

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

Use part of a larger image to fill in the sprite.

这可以通过使用 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),你会得到类似的结果:

enter image description here

关于ios - 为无尽的运行游戏创建动态大小的 SKSpriteNode 平台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593402/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4