How do I change just the starting point of an existing UIBezierPath?

47 Views Asked by At

How do I change just the starting point of an existing UIBezierPath? .. and leave all other points the same?

I have definitely seen many posts on how to do this .. honestly, I just do not understand many of them

My existing path has one .move(to:) and many .addLine(to:)

My goal is:

(1) replace the .move(to:) with .addLine(to:) and then (2) change one of the .addLine(to:) with .move(to:)

All other CGPoints stay the same.

In order to get the new starting point, I set:

savedPathPoint = myPath.currentPoint

when I stop the following motion.

At some point, I want to resume this following motion with the new starting point = savedPathPoint via

    myPath.move(to: savedPathPoint)

    let myAction = SKAction.follow(
                               myPath.cgPath,
                               asOffset: false,
                               orientToPath: true,
                               duration: 0.1)
    mySprite.run(myAction)

When I look at the above problem description, it really appears simple.

Nevertheless, its implementation alludes me.

Thanks bunches in advance for any hints whatsoever.

1

There are 1 best solutions below

1
DonMag On

One .move(to:) and 8 .addLine(to:) means 9 points total. It will take almost no time to "re-build" the path.

Assuming you have:

var pts: [CGPoint]   // an array of 9 points
var startIDX: Int    // the index in the array where you want to "start"

you can use a func like this:

private func generatePath(from ptsArray:[CGPoint], startingAt: Int) -> CGPath {

    var idx = startingAt
    
    if idx > pts.count {
        idx = 0
    }
    
    var ptsCopy = Array(ptsArray[idx...])
    ptsCopy.append(contentsOf: ptsArray[0..<idx])
    
    let pth = CGMutablePath()
    pth.move(to: ptsCopy.removeFirst())
    while !ptsCopy.isEmpty {
        pth.addLine(to: ptsCopy.removeFirst())
    }
    
    // pth is now the same path, but
    //  starting at pts[idx] and
    //  ending at pts[idx-1]

    return pth
    
}

and call it with:

let newPath: CGPath = generatePath(from: pts, startingAt: startIDX)