Clamping camera around the background of a scene in SpriteKit

前端 未结 2 892
别跟我提以往
别跟我提以往 2021-01-03 02:18

so I have a base game setup that can be found at the bitbucket link below:

Game link

I\'m currently having a hard time understanding how to translate the cam

2条回答
  •  感动是毒
    2021-01-03 03:06

    I didn't use your code. I made a sample project and got this working.

    heres my code

    import SpriteKit
    
    class GameScene: SKScene {
    
        let world = SKSpriteNode(imageNamed: "world.jpg")
        let player = SKSpriteNode(color: SKColor.greenColor(), size: CGSizeMake(10, 10))
    
        var cam: SKCameraNode!
    
        override init(size: CGSize) {
            super.init(size: size)
            print(world.size)
            addChild(world)
            addChild(player)
    
            world.zPosition = 1
            player.zPosition = 2
    
            cam = SKCameraNode()
            self.camera = cam
            addChild(cam)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
            for touch: AnyObject in touches {
                let location = touch.locationInNode(self)
    
                player.position = location
            }
        }
    
        override func touchesMoved(touches: Set, withEvent event: UIEvent?) {
            for touch: AnyObject in touches {
                let location = touch.locationInNode(self)
    
                player.position = location
            }
        }
    
        func clampCamera(){
    
            func clamp(inout input: CGFloat, num1: CGFloat, num2: CGFloat) {
                if input < num1 {
                    input = num1
                }
                else if input > num2 {
                    input = num2
                }
            }
    
            let lBoundary = -world.size.width/2 + size.width/2
            let rBoundary = world.size.width/2 - size.width/2
            let bBoundary = -world.size.height/2 + size.height/2
            let tBoundary = world.size.height/2 - size.height/2
    
            clamp(&camera!.position.x, num1: lBoundary, num2: rBoundary)
            clamp(&camera!.position.y, num1: bBoundary, num2: tBoundary)
    
        }
    
        override func update(currentTime: NSTimeInterval) {
            camera!.position = player.position
            clampCamera()
        }
    }
    

    this is the same image i used as my "world" http://i.imgur.com/XhZbh8q.jpg

提交回复
热议问题