Search code examples
iosswiftsprite-kitskspritenodeskphysicsbody

How to attach particles to moving object


I've created an PowerUpTrail.sks (particle thingy) And I'm trying to attach it to a moving object

func SpawnPowerUp(){

    let PowerUp = SKSpriteNode(imageNamed: "PowerUp.png")
    let MinValue = self.size.width / 8
    let MaxValue = self.size.width - 20
    let SpawnPoint = UInt32(MaxValue - MinValue)
    PowerUp.position = CGPoint(x: CGFloat(arc4random_uniform(SpawnPoint)), y: self.size.height - 100)

    //Physics
    PowerUp.physicsBody = SKPhysicsBody(rectangleOfSize: PowerUp.size)
    PowerUp.physicsBody?.categoryBitMask = PhysicsCategory.PowerUp //Sätter unikt ID för Enemy, hämtat från PhysicsCategory som vi gjorde där uppe
    PowerUp.physicsBody?.contactTestBitMask = PhysicsCategory.PowerUp //Kolla om Enemy nuddar Bullet
    PowerUp.physicsBody?.affectedByGravity = false
    PowerUp.physicsBody?.dynamic = true

    let action = SKAction.moveToY(-128, duration: 5)
    let actionDone = SKAction.removeFromParent()
    PowerUp.runAction(SKAction.sequence([action, actionDone]))
    PowerUp.runAction(SKAction.rotateByAngle(5, duration: 5))


    /* this does not work!
    let PowerUpTrail = SKEmitterNode(fileNamed: "PowerUpTrail.sks")
    PowerUpTrail!.targetNode = self
    PowerUpTrail!.position = PowerUp.position
    self.addChild(PowerUpTrail!)
    */

    self.addChild(PowerUp)

}

The particlethingy spawns but it doesnt follow the object. How do I solve this?


Solution

  • The simplest way to make one node's position track another is to use the node hierarchy: make the particle emitter a child node of the powerup sprite.

    let powerUp = SKSpriteNode(imageNamed: "PowerUp.png")
    // ...
    let powerUpTrail = SKEmitterNode(fileNamed: "PowerUpTrail.sks")!
    powerUpTrail.targetNode = self
    powerUp.addChild(powerUpTrail)
    

    (Also note some Swift style tips: initial-cap is conventionally for type names only; use initial-lowercase for variable names. And unwrap your optional from SKEmitterNode(fileNamed:) once when you create it instead of every time you use it thereafter.)