我试图创建一个游戏,你需要避免对象(节点),我不想在一个随机位置(屏幕外,在右边)生成这些节点,通过一个动作,节点越过屏幕到左边。但是我怎样才能创建一个好的随机生成,这样就不会有两个节点在同一个位置或者太近。
我在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)


}

我有第二个问题,想象一个游戏,你需要避开物体,但你可以跳到它上面,有没有可能检测到用户是否与节点侧面碰撞,或者他是否跳到了节点顶部。我认为还有一种方法比在侧面创造一个物理体,在顶部创造一个物理体!
谢谢你的帮助!

最佳答案

对于问题1:保留一个可能的地方的列表,你可以从中产生一个敌人。当你制造敌人时,从列表中删除。当敌人完成行动并被摧毁/离开屏幕时,替换其在列表中的起始位置。每当你掷骰子随机产生一个敌人时,你实际上只是从你的列表中选择可能的开始位置。

//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进行比较,就可以知道你是在顶部还是在侧面。

关于swift - Swift-良好的随机节点生成SpriteKit,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28884172/

10-11 09:02
查看更多