【问题标题】:Array with nodes at each index每个索引都有节点的数组
【发布时间】:2015-01-22 17:26:29
【问题描述】:

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

【问题讨论】:

    标签: arrays swift random sprite-kit


    【解决方案1】:

    当你创建一个宝石时,你需要从数组中移除它的图像和位置,这样其他的宝石就不能和它一样了:

    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
    
    }
    

    【讨论】:

    • 感谢您的回答!但是在生成随机宝石的那一行,我得到了错误:在调用中缺少参数“大小”的参数!
    • 在 didMoveToView 函数中
    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2022-07-29
    • 1970-01-01
    • 2016-05-18
    • 2016-11-08
    相关资源
    最近更新 更多