Child not moving when parent node moves?

2020-04-19 19:23发布

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

1条回答
够拽才男人
2楼-- · 2020-04-19 19:37

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.

查看更多
登录 后发表回答