【问题标题】:How to prevent spawning overlap in swift sprite kit?如何防止快速精灵套件中的产卵重叠?
【发布时间】:2015-06-28 02:06:51
【问题描述】:

如果我试图在屏幕的 2 个已定义区域(顶部和底部以及它们无法生成的中间部分)中生成敌人,如何防止它们生成在每个区域的顶部或太靠近每个区域其他 。

我的精灵在屏幕上相对较小,我在这里找到的唯一建议是创建一个可能的位置数组,每次使用其中一个位置时将其从列表中删除,但首先我什至不知道那会是什么样子,其次我有很多可能的位置,因为我正在使用 5px 高的精灵,我希望它们能够在该区域清晰后重生。

我选择顶部或底部的方法只是选择一个随机数 1 或 2,根据我有 2 个函数可以将它们置于顶部或底部。

我只需要没有两个物体在一个球的直径范围内产生。任何想法如何将其纳入我的产卵?

编辑:

  //Create your array and populate it with potential starting points
   var posArray = Array<CGPoint>()
   posArray.append((CGPoint(x: 1.0, y: 1.0))
   posArray.append((CGPoint(x: 1.0, y: 2.0))
   posArray.append((CGPoint(x: 1.0, y: 3.0))

   //Generate an enemy by rolling the dice and 
   //remove its start position from our queue
   let randPos = Int(arc4random()) % posArray.count
   posArray[randPos]
   posArray.removeAtIndex(randPos)

   ...

   //Play game and wait for enemy to die
   //Then repopulate the array with that enemy's start position
   posArray.append(enemyDude.startPosition)

这是我找到的建议,但这会给出我不知道如何修复的“预期分隔符”错误。

真的,我必须在 X 和 Y 上创建一个巨大的可能位置数组,覆盖所有区域,还是有更好的方法来做到这一点?

【问题讨论】:

    标签: swift sprite-kit


    【解决方案1】:

    通过使用intersectsNode(_ node: SKNode) -&gt; Bool,不在另一个之上生成一个节点就足够了。

    至于不要产卵太近,那是另一回事了。您可以做到这一点的唯一方法是将所有当前节点都放在一个数组中,枚举数组并检查每个节点的位置与产卵节点的位置。根据你的参数,你要么产卵,要么不产卵。


    我不精通 Swift,所以你必须自己翻译代码。

    -(void)testMethod {
    
        // an array with all your current nodes
        NSMutableArray *myArray = [NSMutableArray new];
    
        // the potential new spawn node with the proposed spawn position
        SKSpriteNode *mySpawnNode = [SKSpriteNode new];
    
        BOOL tooClose = NO;
    
        // enumerate your node array
        for(SKSpriteNode *object in myArray) {
    
            // get the absoulte x and y position distance differences of the spawn node
            // and the current node in the array
            // using absolute so you can check both positive and negative values later
            // in the IF statement
            float xPos = fabs(object.position.x - mySpawnNode.position.x);
            float yPos = fabs(object.position.y - mySpawnNode.position.y);
    
            // check if the spawn position is less than 10 for the x or y in relation
            // to the current node in the array
            if((xPos < 10) || (yPos < 10))
            tooClose = YES;
        }
    
        if(tooClose == NO) {
            // spawn node
        }
    }
    

    请注意,数组应该是一个属性,而不是在我在示例中拥有的范围内声明。

    【讨论】:

    • 作为一个刚刚起步的人,您给出的产卵过于接近的解决方案是否会成为一个难以解决的怪物?我肯定要查找如何在那里执行几乎每一步。如果我将其简化并说“机器人部分有 5 个 Y 值,顶部有 5 个 y 值,我将一次让 1 个人随机出现在 X 上”之类的话,是否可以简化解决方案全部?只要每个部分一次只有 1 个,那么在这一点上,亲密关系就不会那么重要了。如果你不介意,我该如何开始这样的事情?
    • 太棒了,非常感谢您抽出宝贵的时间来做这件事。欣赏!
    • @Swiftaccnt - 乐于助人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 2015-05-08
    • 2016-12-07
    • 2020-04-17
    相关资源
    最近更新 更多