【问题标题】:Randomize different enemy in spritekit to move towards player随机化 spritekit 中的不同敌人以向玩家移动
【发布时间】:2017-01-16 14:54:43
【问题描述】:

我想知道是否有人可以回答我的问题。我在 Sprite-kit 中使用纹理图集创建了 3 个不同的敌人动画,我想知道是否有一种方法可以在游戏开始时随机选择一个敌人向玩家移动。

TextureAtlas = SKTextureAtlas(named: "zombies.atlas")
for i in 1...TextureAtlas.textureNames.count {
    let Z = "z\(i).png"
    zombieArray.append(SKTexture(imageNamed: Z))
}


TextureAtlas = SKTextureAtlas(named: "baldzomb.atlas")
for i in 1...TextureAtlas.textureNames.count {
    let bald = "baldzomb_\(i).png"
    baldArray.append(SKTexture(imageNamed: bald))
}

TextureAtlas = SKTextureAtlas(named: "crawler.atlas")
for i in 1...TextureAtlas.textureNames.count {
    let Name = "crawler_\(i).png"
    crawlerArray.append(SKTexture(imageNamed: Name))

}

【问题讨论】:

  • 你能发布你尝试过的东西吗
  • 我还没有尝试过,我正在考虑在我的 spawnEnemy 函数中创建一个“possibleEnemy”函数。关于实现这一目标的任何想法?

标签: swift animation sprite-kit texture-atlas


【解决方案1】:

你可以这样做:

class GameScene: SKScene {


    let storage = [
        SKSpriteNode(color:.brown, size:CGSize(width: 50, height: 50)),
        SKSpriteNode(color:.white, size:CGSize(width: 50, height: 50)),
        SKSpriteNode(color:.black, size:CGSize(width: 50, height: 50)),
        ]

    func getRandomSprite(fromArray array:[SKSpriteNode])->SKSpriteNode{

        return array[Int(arc4random_uniform(UInt32(array.count)))]
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

        let sprite = getRandomSprite(fromArray: storage)

        if let location = touches.first?.location(in: self){

            if let copy = sprite.copy() as? SKSpriteNode {
                //sprite can have only one parent, so I add a copy, just because of better example
                copy.position = location
                addChild(copy)
            }
        }
    } 
}

所以基本上你有一个精灵/纹理/任何数组,你根据数组长度生成随机索引,并返回一个随机元素。您也可以进行扩展,然后执行yourArray.random 之类的操作。

【讨论】:

  • @The1steven2 这个答案是正确的。它会正确响应随机选择的任何这些敌人。我不明白您为什么要发布与随机选择敌人无关的 textureAtlas 的构造。你还想做什么?
  • @AlessandroOrnano,你看到textureAtlas的原因是我在回答问题后编辑了标题。
  • 好吧,你也应该改变你的问题,因为这样是难以理解的。在您的第一个请求下方添加新请求,否则在您的更改之前回答的问题和用户都不一致
  • @The1steven2 通常你不应该那样做。你应该问一个新问题......
  • 好吧,但是请将此问题重新更改为正确的标题。我无法理解发生了什么。谢谢你。并标记答案或此线程无缘无故保持打开状态
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 1970-01-01
  • 2015-02-16
  • 2021-12-03
  • 2020-05-11
  • 2023-02-08
  • 1970-01-01
相关资源
最近更新 更多