Norbert
Norbert

Reputation: 2771

Multiple SKSpriteNodes as one Node in Swift

I'm trying to create a simplified Dr. Mario like game where I have a pill shaped object, each half with their own color.

The pills can be stacked on top of each other and I need to find out via collision detection if two similar colors have collided.

What I tried

  1. I created an SKSpriteNode subclass where I generated half of the pill with its color and spawned two in my scene. I positioned them near each other and created a fixed joint between them. The problem is that I couldn't rotate them as if they were a single Node (there's an open question regardin this issue)

  2. I created two SKSpriteNode subclasses. The first one is just like the one above, returning half a pill, but instead of getting called from the scene, these get called from the second subclass, which returns the pill as a single node into the scene. In this scenario, the rotation works, but I can't figure out how to create a joint between them and add that joint to the physicsWorld from outside the scene.

Either way, neither of my solutions seem okay. How would you go about creating the pill object?

Upvotes: 3

Views: 339

Answers (2)

Kawin P.
Kawin P.

Reputation: 188

I would just create an SKNode subclass with two SKSpriteNode references to the left and the right half of the pill and add these two sprite nodes as children.

Something like this.

class Pill: SKNode {
    var left: SKSpriteNode?
    var right: SKSpriteNode?

    func setup() {
        left = SKSpriteNode()
        /* Setup left half of the pil */
        addChild(left!)

        right = SKSpriteNode()
        /* Setup right half of the pil */
        addChild(right!)
    }
}

Upvotes: 1

Adam Eri
Adam Eri

Reputation: 965

I would not bother having two nodes for the object. The colour is just the texture after all. I would create one SKSpriteNode subclass, one physicsBody and store the rest as attributes. Then on collision you do the calculation on sides and colorus and rotaion.

enum PillColor {
  case red
  case blue
  case yellow
}

class Pill: SKSpriteNode { 
  var rightSide: PillColor?
  var leftSide: PillColor?
  var rotation: Int
}

In the SKPhysicsContactDelegate's didBegin(_ contact) method you can use the contactPoint property of the SKPhysicsContact to know where the two actually met.

Upvotes: 1

Related Questions