2017-07-08 96 views
3

enter image description here如何將SKLabelNode與其父SKShapeNode一起旋轉?

當長按屏幕,用下面的代碼創建球:

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。

+0

在哪裏:自己只有2圖像只用幾行重構的平你讓球旋轉?你可以顯示這個代碼嗎? – ColdSteel

+0

@ColdSteel我已經發布了代碼。我在'override func update(_ currentTime:TimeInterval)' – jdleung

+0

'num.zRotation = ball.zRotation'中更新了他們的zRotation,但是什麼改變了球zRotation? 我建議你在更新方法內記錄ball.zRotation並告訴我它是否更改。附:你不需要將num的Z旋轉與球同步,而num是球的子球,它將隨着球旋轉 – ColdSteel

回答

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) 
} 

但現在比較,與T

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)

+0

,如果有許多不同的紋理,你會做什麼? :)不要忘記地圖集。 – Whirlwind

+0

@Whirlwind我還沒有使用過地圖集呢! – Fluidity

+0

我不得不downvote你再笑 – Whirlwind

相關問題