我如何正确地使SKLabelNode跟随具有物理特性的物体?

问题描述 投票:0回答:1

我创建了一个行为非常简单的类:该类的每个对象都将是一个正方形,顶部有一个名称,它们将在屏幕上随机浮动。

class XSquare: SKNode {

    private var squareShape: SKSpriteNode
    private var text: SKLabelNode

    init() {
        // Sets up the square
        squareShape = SKSpriteNode(color: .red, size: CGSize(width: 100, height: 100))

        // Sets up the text
        text = SKLabelNode(text: "Here goes the name")
        text.position = CGPoint(x: 0, y: 100)

        // Calls the super initializator
        super.init()

        // Sets up the square
        squareShape.physicsBody = SKPhysicsBody(rectangleOf: squareShape.size)
        squareShape.physicsBody?.categoryBitMask = squareBitMask
        squareShape.physicsBody?.collisionBitMask = wallBitMask
        squareShape.physicsBody?.velocity = CGVector(dx: 10, dy: 10)
        squareShape.physicsBody?.angularVelocity = CGFloat(5)
        squareShape.physicsBody?.allowsRotation = true
        squareShape.physicsBody?.pinned = false
        squareShape.physicsBody?.affectedByGravity = false

        addChild(squareShape)
        addChild(text)
    }
}

之所以在该课程中使用SKNode,是因为我想在每个正方形的顶部提供一个小文本(名称指示符)。一切看起来都很好,但是当我运行代码时,名称保持不变,而正方形在屏幕上随机移动(可能是因为我不是使用SKAction而是使用PhysicsBody来移动正方形)。另一方面,如果我使用squareShape.addChild(text),则文本也会按照正方形的物理场旋转。

我是使用SpriteKit的新手,我确定自己缺少一些东西。谁能帮我理解?

xcode sprite-kit skphysicsbody
1个回答
0
投票

只需让您的文本节点做相反的角度即可。如果形状向左旋转10度,则文本向右旋转10度。

这里是如何执行此操作的示例。

class XSquare: SKNode {

    private var squareShape: SKSpriteNode
    private var text: SKLabelNode

    init() {
        // Sets up the square
        squareShape = SKSpriteNode(color: .red, size: CGSize(width: 100, height: 100))

        // Sets up the text
        text = SKLabelNode(text: "Here goes the name")
        text.position = CGPoint(x: 0, y: 100)

        // Calls the super initializator
        super.init()

        // Sets up the square
        squareShape.physicsBody = SKPhysicsBody(rectangleOf: squareShape.size)
        squareShape.physicsBody?.categoryBitMask = squareBitMask
        squareShape.physicsBody?.collisionBitMask = wallBitMask
        squareShape.physicsBody?.velocity = CGVector(dx: 10, dy: 10)
        squareShape.physicsBody?.angularVelocity = CGFloat(5)
        squareShape.physicsBody?.allowsRotation = true
        squareShape.physicsBody?.pinned = false
        squareShape.physicsBody?.affectedByGravity = false

        addChild(squareShape)
        squareShape.addChild(text)
    }
}

func didFinishUpdate(){
     text.zRotation = -squareShape.zRotation
}
© www.soinside.com 2019 - 2024. All rights reserved.