以编程方式创建受约束的物理区域,SpriteKit

时间:2016-02-03 11:58:50

标签: ios swift sprite-kit

我想要两个区域,如下图所示,黄色区域包含精灵。例如,我希望在黄色区域中有球弹跳并反射出黄色区域的边界。如何在不使用sks文件的情况下以编程方式执行此操作?

enter image description here

1 个答案:

答案 0 :(得分:3)

使用+bodyWithEdgeLoopFromRect:

创建基于边缘的物理实体
override func didMoveToView(view: SKView) {

    //Setup scene's physics body (setup the walls)
    physicsBody = SKPhysicsBody(edgeLoopFromRect: frame)

    let yellowSprite = SKSpriteNode(color: .yellowColor(), size: CGSize(width: 300, height: 300))
    yellowSprite.position = CGPoint(x: frame.midX, y: frame.midY)

    //Create the rectangle which will represent physics body.
    let rect = CGRect(origin: CGPoint(x: -yellowSprite.size.width/2, y: -yellowSprite.size.height/2), size: yellowSprite.size)
    yellowSprite.physicsBody = SKPhysicsBody(edgeLoopFromRect: rect)

    addChild(yellowSprite)

    //Add Red ball "inside" the yellow sprite
    let red = SKShapeNode(circleOfRadius: 20)
    red.fillColor = .redColor()
    red.strokeColor = .clearColor()
    red.position = yellowSprite.position
    red.physicsBody = SKPhysicsBody(circleOfRadius: 20)
    red.physicsBody?.restitution = 1
    red.physicsBody?.friction = 0
    red.physicsBody?.affectedByGravity = false

    addChild(red)

    red.physicsBody?.applyImpulse(CGVector(dx: 20, dy: 15))

}

关于rect参数:

  

定义边缘的矩形。指定了矩形   相对于拥有节点的起源。

希望这有帮助!