Update Function Does Not Keep Up With Moving Sprit

2019-09-14 18:39发布

问题:

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))

    }
}