如何使用其父SKShapeNode在公司中轮换SKLabelNode?

时间:2017-07-08 10:11:31

标签: ios swift sprite-kit skspritenode skshapenode

enter image description here

按屏幕时,使用以下代码创建球:

var n = 1
func addBall(_ x:CGFloat){
    let numShape =  SKShapeNode(circleOfRadius: 30)
    numShape.name  = "ball"
    numShape.position = CGPoint(x: x, y: frame.maxY-40)
    numShape.physicsBody = SKPhysicsBody(circleOfRadius: 30)
    numShape.fillColor = SKColor.white
    numShape.physicsBody?.density = 0.1
    numShape.physicsBody?.affectedByGravity = true
    numShape.physicsBody?.friction = 0;
    numShape.physicsBody?.restitution = 0.6
    numShape.physicsBody?.allowsRotation = true
    numShape.physicsBody?.isDynamic = true

    let numLabel = SKLabelNode(fontNamed: "Helvetica")
    numLabel.text = "\(n)"
    numLabel.name = "\(n)"
    numLabel.fontColor = .red
    numLabel.position = CGPoint(x: 0, y: 0)
    numLabel.verticalAlignmentMode = .center

    numShape.addChild(numLabel)
    self.addChild(numShape)

    n += 1
}

球可以旋转,但是他们的childNode numlabel不与它们一起旋转。我尝试更新他们的zRotation,如下所示:

   override func update(_ currentTime: TimeInterval) {
        self.enumerateChildNodes(withName: "ball") {
            node, stop in
            if (node is SKShapeNode) {
                let ball = node as! SKShapeNode
                let num = ball.children[0]
                num.zRotation = ball.zRotation
            }
        }

    }

他们仍然拒绝轮换。如果我像num.zRotation = 2一样直接更改zRotation,它们就会起作用。

如何让它们与SKShapeNode一起轮换?

THX。

1 个答案:

答案 0 :(得分:1)

您需要将摩擦力设置为0以外的数字。

另外,关于形状节点性能:

查看50个形状底部的绘图计数:

enter image description here

for _ in 1...50 {
  let x = arc4random_uniform(UInt32(frame.maxX));
  let xx = CGFloat(x) - size.width/4

  let y = arc4random_uniform(UInt32(frame.maxY))
  let yy = CGFloat(y) - size.width/4

  let shape = SKShapeNode(circleOfRadius: 50)
  shape.strokeColor = .blue
  shape.lineWidth = 1
  shape.position = CGPoint(x: xx, y: yy)
  addChild(shape)
}

但现在将其与只有2行绘制的图像进行比较,只需几行重构:

func addFiftySprites() {

  let shape = SKShapeNode(circleOfRadius: 50)
  shape.strokeColor = .blue
  shape.lineWidth = 1

  let texture = SKView().texture(from: shape)

  for _ in 1...50 {
    let x = arc4random_uniform(UInt32(frame.maxX));
    let xx = CGFloat(x) - size.width/4

    let y = arc4random_uniform(UInt32(frame.maxY))
    let yy = CGFloat(y) - size.width/4

    let sprite = SKSpriteNode(texture: texture)
    sprite.position = CGPoint(x: xx, y: yy)

    addChild(sprite)
  }
}

enter image description here

这里的魔力是使用let texture = SKView().texture(from: <SKNode>)将形状转换为精灵:) let sprite = SKSpriteNode(texture: texture)