Update Function Does Not Keep Up With Moving Sprite

点点圈 提交于 2019-12-25 16:51:42

问题


I have two sprites which a flush against each other. I'm moving one of the sprites around using a SKAction and moving the other sprite using the update function. Every time the update function is called, it calculates the position the second sprite needs to be at so that it continues to be flush against the first sprite.

However, it seems the update function can not move the second sprite fast enough, as a gap appears between the two sprites.

I assume the SKAction repositioning of the first sprite is actioned after the update function is called, and this short delay creates the gap, but I'm only guessing.

I know I can add the second sprite as child to the first sprite to remove the gap, but I can't do that, for reason which will be to long to explain.

Anyway long story short, has anybody got an idea or how to make the update function more precise or how to remove the gap?

Example code that I'm using for testing below:

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    let square1 = SKSpriteNode(texture: nil, color: UIColor.black, size: CGSize(width: 50, height: 50))
    let square2 = SKSpriteNode(texture: nil, color: UIColor.black, size: CGSize(width: 50, height: 50))

    override func didMove(to view: SKView) {

        backgroundColor = UIColor.white
        anchorPoint = CGPoint(x: 0.5, y: 0.5)

        addChild(square1)

        square2.position.x = square1.position.x + square1.size.width/2 + square2.size.width/2
        addChild(square2)

        let moveSideToSide = SKAction.sequence([

            SKAction.moveTo(x: -50, duration: 1),
            SKAction.moveTo(x: 50, duration: 1)

            ])

        square1.run(SKAction.repeatForever(moveSideToSide))

    }

    override func update(_ currentTime: TimeInterval) {

        square2.position.x = square1.position.x + square1.size.width/2 + square2.size.width/2

        // or - they both create a gap

        square2.run(SKAction.moveTo(x: square1.position.x + square1.size.width/2 + square2.size.width/2, duration: 0))

    }
}

来源:https://stackoverflow.com/questions/43819201/update-function-does-not-keep-up-with-moving-sprite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!