Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get SKCameraNode to follow a hero Spritenode

I can't seem to figure this out. I've tried many different things and none of them seem to work. With my current code, the camera and the hero never line up and the scene seems to jump pretty far when I touch the screen. All I want to do is when I touch the screen have the hero move to the touch point and have the camera follow him. Is there some way to lock the camera to the hero spritenode?

import SpriteKit


let tileMap = JSTileMap(named: "level2.tmx")
let hero = SKSpriteNode(imageNamed: "hero")
let theCamera: SKCameraNode = SKCameraNode()

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        /* Setup your scene here */

       self.anchorPoint = CGPoint(x: 0, y: 0)
       self.position = CGPoint(x: 0, y: 0)

        hero.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))



        hero.xScale = 0.5
        hero.yScale = 0.5
        hero.zPosition = 2

        tileMap.zPosition = 1


        tileMap.position = CGPoint(x: 0, y: 0)
        self.addChild(tileMap)
        self.addChild(hero)
        self.addChild(theCamera)

        self.camera = theCamera


    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */

        for touch in touches {

            let location = touch.locationInNode(self)

            let action = SKAction.moveTo(location, duration: 1)

            hero.runAction(action)



        }

            }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */

        self.camera?.position = hero.position
    }
}
like image 777
Bill Avatar asked Sep 21 '15 04:09

Bill


1 Answers

The reason why you saw the scene jumped pretty far is because the scene.size doesn't equal to the screen size. I guess you might initialize your first scene like this:

// GameViewController.swift
if let scene = GameScene(fileNamed:"GameScene") {...}

That code will load GameScene.sks whose size is 1024*768 by default. But since you add your SKSpriteNode programmatically, you can initialize the scene in this way to fit the screen size:

// GameViewController.swift
// Only remove if statement and modify
let scene = GameScene(size: view.bounds.size) ...

This will solve most of the problem you have. Moreover, I suggest moving the camera node using SKAction:

override func update(currentTime: CFTimeInterval) {
    let action = SKAction.moveTo(hero.position, duration: 0.25)
    theCamera.runAction(action)
}

The last thing, add this line to align the camera with your hero at the start:

self.camera?.position = hero.position
like image 188
WangYudong Avatar answered Sep 29 '22 12:09

WangYudong