如何使物理体粘附在节点锚点上

How to make physics bodies stick to nodes anchor points

我在场景中间设置了四个方块,上面设置了各种锚点。点击时,它们会一起移动并根据位置分开:

 func rotate(angle : CGFloat, animated : Bool) {
    var rotateAction : SKAction!

    if animated {
        rotateAction = SKAction.rotateByAngle(angle, duration: 0.6)
    }
    else {
        rotateAction = SKAction.rotateByAngle(angle, duration: 0)
    }
    for node in self.children as! [SKSpriteNode] {

        node.runAction(rotateAction)
    }
}

}

我遇到的问题是节点的物理实体严格停留在锚点上,而不是节点本身,这给我带来了一大堆问题。我怎样才能让每个节点都有我想要的锚点,并让物理体直接留在节点上?如有必要,将 post 更多代码。

你需要将锚点应用到物理体上,它并不知道精灵是什么,它只是精灵使用的另一条信息,所以使用下面的计算来确定精灵的中心应该在哪里是,并将其应用于物理体,以便它可以移动:

 let centerPoint = CGPointMake(sprite.size.width / 2 - (sprite.size.width * sprite.anchorPoint.x), sprite.size.height / 2 - (sprite.size.height * sprite.anchorPoint.y))
 sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size, center: centerPoint)

Swift 3+:

 let centerPoint = CGPoint(x:sprite.size.width / 2 - (sprite.size.width * sprite.anchorPoint.x), y:sprite.size.height / 2 - (sprite.size.height * sprite.anchorPoint.y))
 sprite.physicsBody = SKPhysicsBody(rectangleOf: sprite.size, center: centerPoint)

文字较少:

 let centerPoint = CGPoint(x:sprite.size.width * (0.5 - sprite.anchorPoint.x), y:sprite.size.height *(0.5 - sprite.anchorPoint.y))