2
votes

I'm trying to figure a way to track a postions for multiple nodes, that spwan randomly on the screen so i can make a changes to them while moving when the reach random postion.

the nodes just move along the x axis and i want to be able to generate random number from 0 to postion.x of the ball, and change the color when it reachs the postion

override func update(currentTime: CFTimeInterval)

i tried tacking changes in update method but as soon as new node appers i lost track of the previos one

i also tried

        let changecolor = SKAction.runBlock{
        let wait = SKAction.waitForDuration(2, withRange: 6)
        let changecoloratpoint = SKAction.runBlock { self.changecolorfunc(self.ball)}
        let sequence1 = SKAction.sequence([wait, changecoloratpoint])
        self.runAction(SKAction.repeatAction(sequence1, count: 3))
    }

but it doesn't give me any control over the random postion

2

2 Answers

1
votes

You have already all you needed.

Suppose you have a reference for your node:

var sprite1: SKSpriteNode!

And you want to spawn it to a random position (an example method..):

self.spawnToRandomPos(sprite1)

And suppose you want to moveTo your sprite1:

self.sprite1.runAction( SKAction.moveToY(height, duration: 0))

Everytime you check his position you know where is it:

print(sprite1.position)

So to know always your sprite1 position you could do this code and you see all it's movements:

override func update(currentTime: CFTimeInterval) {
    print(sprite1.position)
}

P.S.:

In case you dont have references about your object spawned you can also give a name to a generic object based for example by a word followed to a counter (this is just an example):

for i in 0..<10 {
   var spriteTexture = SKTexture(imageNamed: "sprite.png")
   let sprite = SKSpriteNode(texture: spriteTexture, size: spriteTexture.size)
   sprite.name = "sprite\(i)"
   self.addChild(sprite)
}

After this to retrieve/re-obtain your sprite do:

 let sprite1 = self.childNodeWithName("sprite1")
0
votes

There are probably a hundred different ways of doing this. Here is how I would do it.

in your update func

checkForCollisions()

this will just scroll through "obstacles" that you randomly generate, and place whoever you want the color trigger to happen. They can be anything you want just change the name to match. if they overlap your "ball" then you can color one or the other.

func checkForCollisions() {

    self.enumerateChildNodesWithName("obstacles") { node, stop in

        if let obstacle: Obstacle = node as? Obstacle {

            if self.ball.intersectsNode(obstacle) {

                //color node or ball whichever you want
            }
        }
    }
}