基本上,我想移动角色(玩家)并让世界上的“相机”或场景跟随他们。问题是Apple / xcode没有内置的摄像头节点,如果我试图移动场景,我会收到错误说“SKScene无法移动”的效果。我不想只是移动背景围绕并锁定播放器,因为我希望能够将力量应用于播放器节点。我已经访问了Apple的网站,进入了高级场景处理页面并按照示例进行了操作,但它不起作用。我只需要朝着正确的方向轻推。谢谢!
代码:
(我删除了无关的代码片段)
class PlayScene: SKScene, SKPhysicsContactDelegate {
let world = SKNode()
let player = SKShapeNode(circleOfRadius: 25)
var cannonRotation = 0.0
var fired = false
override func didMoveToView(view: SKView) {
physicsWorld.contactDelegate = self
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.addChild(world)
//Adds the background to the world
//Adds the elements to the scene
player.fillColor = UIColor.whiteColor()
player.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMinY(self.frame)+65+25)
player.zPosition = 2
player.physicsBody = SKPhysicsBody(circleOfRadius: 25)
player.physicsBody?.dynamic = true
player.physicsBody?.restitution = 0.9
player.physicsBody?.categoryBitMask = BodyType.player.rawValue
//Adds the physics properties to GameScene
let physicsGround = SKPhysicsBody(edgeFromPoint: CGPoint(x: CGRectGetMinX(self.frame), y: CGRectGetMinY(self.frame)+65), toPoint: CGPoint(x: CGRectGetMaxX(self.frame), y: CGRectGetMinY(self.frame)+65))
self.physicsBody = physicsGround
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
powerLevel()
totalPower = powerReached * playCannon.powerMultiplier
self.addChild(player)
player.physicsBody?.applyImpulse(CGVector(dx: CGFloat(Float(totalPower)*cosf(Float(cannonRotation))), dy: CGFloat(Float(totalPower)*sinf(Float(cannonRotation)))))
fired = true
}
答案 0 :(得分:1)
覆盖didsimulatePhysics,并在该函数中调用此
self.centerOnNode(player);
这样做,它会调用我们稍后创建的函数,它会发送一个SKNode参数,在您的情况下它是player
节点。接下来创建一个名为centerOnNede
的方法并添加以下参数
func centerOnNode(node: SKNode) {
}
在centerOnNode
函数中添加以下代码行。
var cameraPosition: CGPoint = node.scene?.convertPoint(node.position, fromNode: node.parent!)
cameraPosition.x = 0
let posX = node.parent?.position.x
let posY = node.parent?.position.y
node.parent?.position = CGPointMake(posX! - cameraPosition.x, posY! - cameraPosition.y)
这将使摄像机居中到节点并更新它的位置。代码从这里转换。 How to make camera follow SKNode in Sprite Kit?
答案 1 :(得分:0)
Apple Adventure参考游戏中有how to do this的详细示例。它有Swift和Objective-C两个例子。
总结一下,他们推荐的是你
相机节点会非常有用,但尚未在SpriteKit中实现。
答案 2 :(得分:0)
从iOS 9开始,现在有一个SKCameraNode可以为您完成所有繁重的工作。
只需在didMoveToView函数中添加以下三行代码:
let cameraNode = SKCameraNode()
self.addChild(cameraNode)
self.camera = cameraNode
然后在你的didFinishUpdate函数中,只需将cameraNode的位置设置为你想要它遵循的任何SKSpriteNode。