微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将相机置于swift spritekit中的节点上

我在斯威夫特创造了一个Terraria风格的游戏.我想拥有它,所以玩家节点总是在屏幕的中心,当你向右移动时,这些块就像Terraria一样向左移动.

我目前正在试图弄清楚如何将视图保持在角色的中心.有谁知道实现这个的好方法

解决方法

以下将使相机居中于特定节点.它还可以在设定的时间范围内平滑过渡到新位置.

class CameraScene : SKScene {
    // Flag indicating whether we've setup the camera system yet.
    var isCreated: Bool = false
    // The root node of your game world. Attach game entities 
    // (player,enemies,&c.) to here.
    var world: SKNode?
    // The root node of our UI. Attach control buttons & state
    // indicators here.
    var overlay: SKNode?
    // The camera. Move this node to change what parts of the world are visible.
    var camera: SKNode?

    override func didMovetoView(view: SKView) {
        if !isCreated {
            isCreated = true

            // Camera setup
            self.anchorPoint = CGPoint(x: 0.5,y: 0.5)
            self.world = SKNode()
            self.world?.name = "world"
            addChild(self.world)
            self.camera = SKNode()
            self.camera?.name = "camera"
            self.world?.addChild(self.camera)

            // UI setup
            self.overlay = SKNode()
            self.overlay?.zPosition = 10
            self.overlay?.name = "overlay"
            addChild(self.overlay)
        }
    }


    override func didSimulatePhysics() {
        if self.camera != nil {
            self.centerOnNode(self.camera!)
        }
    }

    func centerOnNode(node: SKNode) {
        let cameraPositionInScene: CGPoint = node.scene.convertPoint(node.position,fromNode: node.parent)

        node.parent.position = CGPoint(x:node.parent.position.x - cameraPositionInScene.x,y:node.parent.position.y - cameraPositionInScene.y)
    }

}

通过移动相机来改变世界上可见的内容

// Lerp the camera to 100,50 over the next half-second.
self.camera?.runAction(SKAction.moveto(CGPointMake(100,50),duration: 0.5))

资料来源:swiftalicio – 2D Camera in SpriteKit

有关其他信息,请查看Apple的SpriteKit Programming Guide(示例:在节点上居中显示场景).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐