Get SKCameraNode to follow the Spritenode hero

I can’t figure it out. I tried a lot of 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 get very close when I touch the screen. All I want to do is when I touch the screen, and the hero moves to the point of touch, and the camera watches him. Is there a way to block the camera for a hero’s sprite?

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 } } 
+6
source share
1 answer

The reason you saw the scene jumped very much because scene.size does not fit the screen size. I think you can initialize your first scene as follows:

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

This code will load GameScene.sks , the default size of which is 1024 * 768. But since you programmatically add SKSpriteNode , you can initialize the scene so that it matches 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 that you have. Moreover, I suggest moving the node camera using SKAction :

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

Last, add this line to align the camera with your hero at the beginning:

 self.camera?.position = hero.position 
+5
source

All Articles