我正在用Swift和Sprite工具包开发一个Xcode项目,我想知道如何选择受径向重力场影响的对象。我现在有两颗恒星和一些行星,每颗恒星都有一个径向重力场。问题是恒星被吸引到自己的重力场。我怎样才能使每个重力场只影响一颗恒星和所有行星,而不影响它所追随的恒星。我知道这和CategoryBitmask和/或FieldBitmask有关系,但我不知道具体怎么做。事先谢谢。下面是恒星和重力场的代码。我不想那个重力场影响那个恒星。

class star: SKSpriteNode {

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")

 }

init(imageNamed: String){
    let imageTexture = SKTexture(imageNamed: imageNamed)

    super.init(texture: imageTexture, color: nil, size: imageTexture.size())

    let radius = self.size.width / 2

    self.physicsBody = SKPhysicsBody(circleOfRadius: radius )
    physicsBody?.dynamic = false

}
}

    let star1 = star(imageNamed: "star")
    let gravityField1 = SKFieldNode.radialGravityField()

    star1.position = CGPoint(x: self.size.width / 4, y: self.size.height / 2)
    star1.physicsBody?.friction = 0
    star1.physicsBody?.linearDamping = 0
    star1.physicsBody?.angularDamping = 0
    star1.physicsBody?.angularVelocity = 0.2
    star1.zPosition = 1
    star1.name = "star"
    addChild(star1)


    gravityField1.enabled = true;
    gravityField1.position = CGPoint(x: self.size.width / 4, y: self.size.height / 2)
    gravityField1.strength = Float(pow(radius1, 2)) * pow(10, -3)

    addChild(gravityField1)

最佳答案

下面是如何设置类别和字段位掩码的示例:
为重力场设置类别位掩码

gravityField1.categoryBitMask = gravityField1Category
gravityField2.categoryBitMask = gravityField2Category

设置位掩模,使每颗恒星都受到另一颗恒星的重力场的影响,但不受其自身的影响。
star1.physicsBody?.fieldBitMask = gravityField2Category
star2.physicsBody?.fieldBitMask = gravityField1Category

设置位掩模,使行星受到两个重力场的影响
planet.physicsBody?.fieldBitMask = gravityField1Category | gravityField2Category

08-07 20:22