且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 spritekit 中沿 UIBezierPath 绘制节点

更新时间:2023-02-01 20:05:39

可以使用SKAction.follow(path:)timingFunction方法来设置你的精灵沿着贝塞尔曲线.通常,您使用 timingFunction 方法来自定义操作的时间,例如,缓入或缓出.在这种情况下,您可以使用它来设置精灵沿路径的起点.

You can use the timingFunction method of SKAction.follow(path:) to set the spacing of your sprites along the bezier path. Typically, you use the timingFunction method to customize the timing of an action, for example, to the ease-in or ease-out. In this case, you can use it to set the starting point of a sprite along a path.

例如,如果您想在贝塞尔曲线路径的中点开始精灵,您可以将 timingFunctiontime 参数偏移 0.5,其中 time 从 0 开始,到 1 结束.

For example, if you want to start the sprite at the midpoint of your bezier path, you can offset the time parameter of the timingFunction by 0.5, where the time starts at 0 and ends at 1.

let move = SKAction.follow(path.cgPath, speed: 100)

move.timingFunction = {
    time in
    return min(time + 0.5, 1)
}

如果你在你的精灵上运行 move 动作,它会从你路径的中点开始,到路径的终点结束.

If you run the move action on your sprite, it will start at the midpoint of your path and end at the path's end point.

这是一个沿贝塞尔曲线路径设置一组精灵的间距的示例

Here's an example to set the spacing for a set of sprites along a bezier path

// Show the path
let shapeNode = SKShapeNode(path: path.cgPath)
shapeNode.strokeColor = UIColor.white
addChild(shapeNode)

// Add 5 sprites to the scene at various points along the path
for i in 1...5 {            
    let move = SKAction.follow(path.cgPath, speed: 100)

    move.timingFunction = {
        time in
        return min(time + 0.1 * Float(i), 1)
    }

    let sprite = SKSpriteNode(color: .blue, size: CGSize(width: 20, height: 20))
    addChild(sprite)
    sprite.run(move)
}