每个索引处有节点的数组

Array with nodes at each index

我正在 Swift 中使用 Sprite Kit 创建游戏,我在 3 个位置生成了三个节点(宝石):

self.size.width * 1/6  // left
self.size.width * 1/6  // middle
self.size.width * 1/6  // right

我创建了一个包含三个位置的数组来随机调用它们:

    let randomX = [self.size.width * 1/6, self.size.width * 3/6, self.size.width * 5/6]   // Array with three positions
    let randomIndex = Int(arc4random_uniform(UInt32(randomX.count)))
    let xPos : CGFloat = randomX[randomIndex]

我还有一个包含三个珠宝节点的数组:

    let randomJewels = [SKSpriteNode(imageNamed: "jewel1"), SKSpriteNode(imageNamed: "jewel2"), SKSpriteNode(imageNamed: "jewel3"),]

然后我设置生成节点的位置和大小:

    let jewel1 = randomJewels[Int(arc4random_uniform(3))]
    jewel1.anchorPoint = CGPointMake(0.5, 0)
    jewel1.position = CGPointMake(xPos, self.size.height / 2)
    jewel1.size.width = 40
    jewel1.size.height = 20
    self.addChild(jewel1)

这三个位置需要由三个随机节点(珠宝)占据,但如果我生成另外两个珠宝,它们可能具有相同的位置,因为它们可能具有三个不同的位置。

如何才能让宝石占据三个位置?不能空位,每个x位都有一颗宝石!谢谢!

创建珠宝时,您需要从数组中删除它的图像和位置,这样其他珠宝就不会与它相同:

var imageNames=["jewel1","jewel2","jewel3"]//Names of jewel images
var xPositions=[size.width*1/6,size.width*3/6,size.width*5/6]//posible x positions

for i in 0..<xPositions.count {//Create one jewel for every x position

    let imageIndex=Int(arc4random_uniform(UInt32(imageNames.count)))
    let jewel=SKSpriteNode(imageNamed: imageNames[imageIndex])
    imageNames.removeAtIndex(imageIndex)//remove this image so no other jewel can have it

    let xPositionIndex=Int(arc4random_uniform(UInt32(xPositions.count)))
    jewel.position=CGPoint(x: xPositions[xPositionIndex], y: size.height/2)
    xPositions.removeAtIndex(xPositionIndex)//remove this position so no other jewel can have it

    //Setup the jewel and add it to the scene

}