每个索引都有节点的数组

时间:2015-01-22 17:26:30

标签: arrays swift random sprite-kit

我正在使用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位置都有一颗宝石!谢谢!

1 个答案:

答案 0 :(得分:0)

当你创建一个宝石时,你需要从阵列中移除它的图像和位置,这样其他宝石就不能与它相同:

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

}