尝试在swift中实现视差效果时滞后(spritekit)

时间:2015-03-12 11:02:51

标签: swift sprite-kit parallax lag gravity

我正在尝试用SpriteKit创建具有视差效果的游戏,但是当我实施我的方法时,我的英雄不时(很快就会震动)(没有观察到模式)......

我写了这个简单的代码来说明方法并且也包含相同的问题。

英雄应该留在屏幕的中央,只有相对于他父母(前景)的位置才会改变。但它时不时地滞后(很快就会在很短的时间内震动)。我还注意到,当我运行游戏时,英雄在非常缓慢地下沉几个像素(可能是5-10),然后在约15秒后开始保持其位置。

我无法弄清楚导致此行为的原因。任何帮助,将不胜感激。我正在测试iPhone 6。

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {


let hero = SKSpriteNode(imageNamed: "hero")
let foreground = SKNode()


required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override init(size: CGSize) {
    super.init(size: size)


    physicsWorld.gravity = CGVector(dx: 0.0, dy: -0.5)
    physicsWorld.contactDelegate = self


    // anchor point of scene is at (x: 0.5, y: 0.5)

    hero.position = CGPoint(x: 0, y: 0)
    hero.physicsBody = SKPhysicsBody(rectangleOfSize: hero.size)
    hero.physicsBody?.dynamic = true
    hero.physicsBody?.allowsRotation = false


    addChild(foreground)
    foreground.addChild(hero)
}


override func update(currentTime: NSTimeInterval) {

    foreground.position = CGPoint(x: 0, y: -(hero.position.y))
}
}

// I need the foreground to move in opposite direction so I can add stars,
// monsters, etc while keeping the player in the view... Update method does 
// this: hero is pulled down by gravity so his y position would be -1 pixel 
// relative to foreground but I assign foreground the opposite y-position of
// hero (+1) and since hero's position relative to foreground is -1, he should 
// be positioned at y-position = 0 which, in this code example, should create 
// an illusion that he is positioned at the center and doesn't move

0 个答案:

没有答案