11

I essentially want to emit confetti particles. Each particle is the same shape, however, I want each particle to be a random colour from a selection of colors I specify.

Is there a way for each emitted particle to have a random color or do I need a separate emitter for each particle color?

asdfg
  • 123
  • 1
  • 6
  • 2
    @sangony I've created the particles, but I have no clue how to get them to be random colours. I looked online for quite a while and couldn't find anything. – asdfg Jun 26 '15 at 17:13

2 Answers2

8

You can use single emitter to achieve what you want:

import SpriteKit


class GameScene: SKScene, SKPhysicsContactDelegate {



    let emitter = SKEmitterNode(fileNamed: "particle")
    let colors = [SKColor.whiteColor(),SKColor.grayColor(),SKColor.greenColor(),SKColor.redColor(),SKColor.blackColor()]


    override func didMoveToView(view: SKView) {


        self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)


        emitter.position = CGPoint(x: 200, y:300)

        emitter.particleColorSequence = nil
        emitter.particleColorBlendFactor = 1.0

        self.addChild(emitter)

        let action = SKAction.runBlock({
            [unowned self] in
            let random = Int(arc4random_uniform(UInt32(self.colors.count)))

            self.emitter.particleColor = self.colors[random];
            println(random)
        })

        let wait = SKAction.waitForDuration(0.1)

        self.runAction(SKAction.repeatActionForever( SKAction.sequence([action,wait])))


    }

}

EDIT:

Try changing duration of wait action to get different results.

You can play with color ramp too (in particle editor) to achieve the same effect:

enter image description here

Or you can use particleColorSequence and SKKeyframeSequence in order to change particle color over its lifetime. Hope this helps.

Whirlwind
  • 14,286
  • 11
  • 68
  • 157
  • But this wouldn't give a mix of colours, like you would need for confetti. You would only get some colour for a second, then another for the next and so on. The particles would all be the same colour, the colour would just change every second. It would look extremely unnatural. Or am I misunderstanding the code? – asdfg Jun 26 '15 at 04:30
  • Yeah, you are right, I forgot to change the duration of wait action. Please check the edit. – Whirlwind Jun 26 '15 at 09:17
0

Just for anyone else who might want an answer to this. There is a framework called SAConfettiView https://github.com/sudeepag/SAConfettiView. Definitely check it out! It worked for me.

Kervon Ryan
  • 684
  • 1
  • 10
  • 20