Swift - 良好的随机节点生成 SpriteKit

Swift - Good random node generation SpriteKit

我尝试创建一个你需要避免 objects(节点)的游戏,我不想在随机位置(屏幕外,右侧)生成这些节点,并且通过一个动作,节点向左穿过屏幕。但是我怎样才能创建一个好的随机生成,使得两个节点不在同一位置或太近。

我在 didMoveToView 方法中有一个计时器:

nodeGenerationTimer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("nodeGeneration"), userInfo: nil, repeats: true)

以及每2秒生成一次节点的函数:

func nodeGeneration() {


    var randomX = CGFloat(Int(arc4random()) % sizeX)
    println(randomX)


    let node = SKSpriteNode(imageNamed: "node")
    node.anchorPoint = CGPointMake(0.5, 0.5)
    node.size.width = self.size.height / 8
    node.size.height = bin.size.width * (45/34)
    node.position = CGPointMake(self.size.width + randomX, ground1.size.height / 2 + self.size.height / 14)
    node.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: node.size.width, height: node.size.height))
    node.physicsBody?.dynamic = false
    self.addChild(node)

    let moveAction = SKAction.moveByX(-1, y: 0, duration: 0.005)
    let repeatMoveAction = SKAction.repeatActionForever(moveAction)
    node.runAction(repeatMoveAction)


}

还有第二个问题,想象一个游戏,你需要躲避object,但你可以跳上去,是否可以检测到用户是否与节点的侧面发生碰撞,或者如果他跳上它的顶部。我认为除了在侧面创建物理 [​​=23=] 并在顶部创建物理之外,还有另一种方法!

感谢您的帮助!

对于问题 1:保留一个可以生成敌人的可能位置的列表。当你创建一个敌人时,从列表中删除。当敌人完成它的动作并且 destroyed/goes 离开屏幕时,然后替换它在列表中的起始位置。每当您掷骰子生成随机敌人时,您实际上只是在列表中的可能开始位置之间进行选择。

//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)

对于问题 2:您可以访问节点的 x 和 y 坐标,因此您可以使用单个物理体适当地处理碰撞。只需将物体的底部 X 与障碍物的顶部 Y 进行比较,您就会知道自己是在顶部还是在侧面。