SpriteKit joint: follow the body

…衆ロ難τιáo~ 提交于 2019-12-07 16:11:26

"All the remaining snake's pieces should follow the head - they should travel exactly the same path that head was some time ago."

You should note that with Physics joints you are likely going to have variance no matter what you do. Even if you have it close to perfect you'll have rounding errors under the hood making the path not exact.

If all the tail parts are equal you can also use a different approach, this is something I've done for a comet tail. Basically the idea is that you have an array of tail objects and per-frame move move the last tail-object always to the same position as the head-object. If the head-object has a higher z-position the tail is drawn below it.

If you need to keep your tail in order you could vary the approach by storing an array of head-positions (per-frame path) and then place the tail objects along that path in your per-frame update call to the snake.

See my code below for example:

These are you head-object variables:

var tails = [SKEmitterNode]()
var tailIndex = 0

In your head init function instantiate the tail objects:

for _ in 0...MAX_TAIL_INDEX
        {
            if let remnant = SKEmitterNode(fileNamed: "FireTail.sks")
            {
                p.tails.append(remnant)
            }
        }

Call the below per-frame:

func drawTail()
{
    if tails.count > tailIndex
    {
        tails[tailIndex].resetSimulation()
        tails[tailIndex].particleSpeed = velocity() / 4
        tails[tailIndex].emissionAngle = zRotation - CGFloat(M_PI_2) // opposite direction
        tails[tailIndex].position = position
        tailIndex = tailIndex < MAX_TAIL_INDEX ? tailIndex + 1 : 0
    }
}

The resulting effect is actually really smooth when you call it from the scene update() function.

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