以编程方式在sprite中创建一个区域

时间:2016-02-02 12:26:44

标签: ios swift sprite-kit

我有一个精灵球,我想只在一个方形区域内反弹。

如何在主框架内以编程方式创建此方形区域,而不是像我在代码段中那样约束整个框架:

let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody

1 个答案:

答案 0 :(得分:0)

试试这段代码。它创建了一个带有SKPhysicsBody的SKNode。然后,您可以将精灵放在此节点中:

    // Create a boundary rectangle. Adjust with your size:
    let boundary = CGRect(x: 100, y: 100, width: 100, height: 100)

    // Create a boundary node
    let boundaryNode = SKNode()

    // Create the PhysicsBody and assign it to the node
    let borderBody = SKPhysicsBody(edgeLoopFromRect: boundary)
    borderBody.friction = 0
    boundaryNode.physicsBody = borderBody

    // Add boundary node to the scene
    self.addChild(boundaryNode)

    // Add your Sprite to the boundaryNode
    boundaryNode.addChild(yoursprite)