Multiple SKSpriteNodes as one Node in Swift

I am trying to create a simplified Dr. Mario like game in which I have a pill shaped object, each half of which has its own color.

The tablets can be stacked on top of each other and I need to find out through collision detection if two similar colors collide.

What i tried

  • I created a subclass SKSpriteNode

    where I created half a pill with its color and spawned two in my scene. I placed them next to each other and created a fixed connection between them. The problem is that I couldn't rotate them as if they were the only Node ( there's an open question in this issue )

  • I created two subclasses SKSpriteNode

    . The first one is similar to the one above, returning half a pill, but instead of being called from the scene, they are called from a second subclass, which returns the pill as a single Node to the scene. In this case, the rotation works, but I can't figure out how to create a connection between them and add that connection to the physical world from outside the scene.

Anyway, none of my solutions looks ok. How are you going to create a tablet object?

+3


source to share


2 answers


I would just subclass SKNode with two SKSpriteNode references on the left and right half of the pill, and add those two sprite nodes as children.

Something like that.



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!)
    }
}

      

+1


source


I wouldn't worry about having two nodes for an object. Color is just texture. I would create one subclass SKSpriteNode

, one physical element, and store the rest as attributes. Then, on collision, you do the calculation by sides, color and rotation.

enum PillColor {
  case red
  case blue
  case yellow
}

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

      



In the method, SKPhysicsContactDelegate

didBegin(_ contact)

you can use the contactPoint

for property SKPhysicsContact

to find out where the two actually met.

+1


source







All Articles