1

I have three nodes the world, the player and "the player vision". Both the world and the vision SKShapeNodes and my player uses a custom subclass of SKShapeNode. When I move the world all the player moves with it, however when I move the player the vision node stays fixed in it's position. What could be the reason for this?

This is my player class:

class Character : SKShapeNode {
    var vision : SKShapeNode
    var spinning = false

    init(size: CGSize) {
        vision = SKShapeNode()

        // Player Shape
        super.init()
        self.path = SKShapeNode(rectOfSize: size).path
        self.fillColor = SKColor.blackColor()
        self.strokeColor = SKColor.blackColor()
        self.name = "Player"

        // Player Physics Body
        self.physicsBody = SKPhysicsBody(rectangleOfSize: self.frame.size)
        self.physicsBody.restitution = 0
        self.physicsBody.allowsRotation = false
        self.physicsBody.categoryBitMask = ColliderType.Player.toRaw()
        self.physicsBody.collisionBitMask = ColliderType.Wall.toRaw()
        self.physicsBody.contactTestBitMask = ColliderType.Wall.toRaw() | ColliderType.Player.toRaw() | ColliderType.Enemy.toRaw()

        // Vision Shape
        vision = SKShapeNode(rectOfSize: CGSize(width: 200, height: 1))
        vision.fillColor = SKColor.greenColor()

        // Vision Physics body
        vision.physicsBody = SKPhysicsBody(rectangleOfSize: vision.frame.size)
        vision.physicsBody.affectedByGravity = false
        vision.physicsBody.categoryBitMask = ColliderType.Vision.toRaw()
        vision.physicsBody.collisionBitMask = 0
        vision.physicsBody.contactTestBitMask = ColliderType.Wall.toRaw()
        self.addChild(vision)
    }
}
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410
  • 1
    hmmm just a hunch: try vision without assigning a physicsbody, not sure if and how SK handles child physicsbodies. It might just cause the vision to separate from its parent because physicsbodies don't normally have parent-child relationships – CodeSmile Jul 25 '14 at 22:45
  • you were right, the strange thing is that I tested making the world a physicsbody and it does work. The problem is that I need to implement collission detection for the vision node, do you know of any solution while keeping it as a child of player? – lisovaccaro Jul 25 '14 at 23:31

1 Answers1

2

The problem is that your vision node is affect by the physics engine separately from its parent due to its own physicsBody. The solution is to set the vision node's position property to CGPoint(0, 0) (or whatever you desire it to be in its parent's coordinate system) in the didSimulatePhysics step of the frame. This will have the result of resetting the vision node to "follow" the parent node at all times.

Attackfarm
  • 512
  • 3
  • 9