隐藏后如何在不同的地方重新生成

How to re-spawn in a different place once unhidden

我想知道如何取消隐藏我的节点,但是一旦取消隐藏就会出现在与原始节点不同的地方。

let x3 = rect.origin.x + CGFloat(arc4random()) % rect.size.width
let y3 = rect.origin.y + CGFloat(arc4random()) % rect.size.height
let randomPoint3 = CGPointMake(x3, y3)
self.greencircle.position = randomPoint3
self.addChild(greencircle)
let wait3 = SKAction.waitForDuration(2.0)
greencircle.hidden = true
let wait23 = SKAction.waitForDuration(1.0)
greencircle.hidden = false

那么一旦 'green circle' 被取消隐藏,你如何保证在与之前不同的位置生成并重复?

要在给定矩形内的随机点生成节点,您可以使用此方法:

 func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{
    return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}

func randomPointWithinRectangle(rectangle: CGRect) -> CGPoint {

    var point : CGPoint = CGPoint()

     point.x = randomBetweenNumbers(rectangle.origin.x + sprite.size.width / 2, secondNum: rectangle.origin.x + rectangle.size.width - sprite.size.width / 2)

    point.y = randomBetweenNumbers(rectangle.origin.y + sprite.size.width / 2, secondNum: rectangle.origin.y + rectangle.size.height - sprite.size.width / 2)


    return point

}

接下来是 hiding/unhiding 部分...请注意,我目前使用的是 Swift 的过时版本 :D,对我有用的可能对你不起作用。但是逻辑是一样的。

为此,您可以使用 SKAction 序列,如下所示:

func startSpawningSprites(){

let wait = SKAction.waitForDuration(0.5)

let fadeOut = SKAction.fadeOutWithDuration(0.5)

let fadeIn = SKAction.fadeInWithDuration(0.3)

//Use weak reference to self to prevent retain cycle. in Swift 2.0 you should use appropriate syntax.
weak var weakSelf = self

let changePosition = SKAction.runBlock({

      weakSelf!.sprite.position = weakSelf!.randomPointWithinRectangle(weakSelf!.rectangle.calculateAccumulatedFrame())
})

let sequence = SKAction.sequence([wait, fadeOut, changePosition, wait, fadeIn])

sprite.runAction(SKAction.repeatAction(sequence, count:10))

}

在这里,代码非常简单明了,它完成了我上面所说的(隐藏、移动和取消隐藏节点)。矩形变量被定义为 属性 只是为了更容易调试。

关于你问题的其他部分..我不确定我是否理解......但我可以试一试。如果您关心节点之间的重叠并且想要避免它,那么您必须检查给定点是否有节点(nodeAtPoint 方法可能很有用)。从理论上讲,这可能会消耗资源。如果对原因感兴趣,请阅读更多内容

编辑:

回答您评论中的问题:

变量精灵和矩形被定义为 GameScene 的属性:

class GameScene:SKScene{

let sprite = SKSpriteNode(color: SKColor.redColor(), size: CGSize(width: 30, height: 30))

//just for debugging purposes
let rectangle = SKSpriteNode(color: SKColor.orangeColor(), size: CGSize(width: 150, height: 150))

override func didMoveToView(view: SKView) {

    setupScene()


    startSpawningSprites()
}


func setupScene(){

    sprite.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame))
    sprite.zPosition = 4
    sprite.name = "sprite" //later on, you can access or enumerate node(s) by name

    addChild(sprite)

    rectangle.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame))
    rectangle.alpha = 0.5
    rectangle.zPosition = 3
    rectangle.name = "rectangle"
    addChild(rectangle)

}

func startSpawningSprites(){
     //...
}

}

最终结果如下所示: