获取allContactedBodies()返回的节点属性?

时间:2014-07-21 21:47:31

标签: ios swift sprite-kit

我试图获取触摸节点的对象列表。我使用了函数player.physicsBody.allContactedBodies。但是,我无法读取节点的名称,也无法读取contactBitMask。当我试图打印body.name时,我收到错误"无法打开可选节点"

这是我现在正在尝试的(滚动到allContactBodies()函数的结尾):

let motionManager = CMMotionManager()
var player = SKShapeNode()
var world = SKShapeNode()
var ledge = SKShapeNode()

override func didMoveToView(view: SKView) {
    let worldSize = view.bounds.size
    self.physicsWorld.contactDelegate = self
    self.size = worldSize
    self.scaleMode = SKSceneScaleMode.AspectFit
    self.name = "Universe"
    //self.physicsWorld.speed = 0.25 // DEBUG

    // Add world
    world = SKShapeNode(rectOfSize: worldSize)
    world.physicsBody = SKPhysicsBody(edgeLoopFromPath: world.path)
    world.fillColor = SKColor.whiteColor()
    world.physicsBody.restitution = 0
    world.physicsBody.friction = 0.1
    world.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2) // Move camera
    world.name = "world"
    self.addChild(world)

    // Add player
    player = SKShapeNode(rectOfSize: CGSize(width: 25, height: 25))
    player.physicsBody = SKPhysicsBody(rectangleOfSize: player.frame.size)
    player.physicsBody.restitution = 0
    player.fillColor = SKColor.blackColor()
    player.strokeColor = SKColor.blackColor()
    player.physicsBody.allowsRotation = false
    player.name = "player"
    world.addChild(player)

    // Add ledge
    ledge = SKShapeNode(rectOfSize: CGSize(width: 100, height: 100))
    ledge.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 100, height: 100))
    ledge.fillColor = SKColor.blackColor()
    ledge.strokeColor = SKColor.blackColor()
    ledge.physicsBody.dynamic = false
    ledge.position = CGPointMake(150, 100)
    ledge.name = "ledge"
    world.addChild(ledge)

    // Accelerometer updates
    motionManager.startAccelerometerUpdates()
}


override func update(currentTime: CFTimeInterval) {
    let bodies = player.physicsBody.allContactedBodies()
    for body : AnyObject in bodies {
        println(String(body.name)) // Produces Error
    }
 }

如果我println(正文),则日志显示:

<SKPhysicsBody> type:<EdgeLoop> representedObject:[<SKShapeNode> name:'world' accumulatedFrame:{{-0.49996948, -0.5}, {360.99997, 569}}]

如何获取每个节点的名称和其他属性?

1 个答案:

答案 0 :(得分:0)

根据错误消息,我猜body没有node(即,它是nil)并且您尝试打开它以访问{节点的{1}}。你可以先测试一下:

name