I am making an app where I am generating points with random position. I want to connect first point with the second one with the line, and that the second with the third, etc.
My issue is that it is connecting second with the third but in the same time the first is being connected with the third one. And I don’t want that. Please help.
This is my code:
struct Dot: Hashable {
var x: CGFloat
var y: CGFloat
}
struct TestShit: View {
@State var lastx = 0.0
@State var lasty = 0.0
@State var dots = [Dot]()
var body: some View {
VStack{
ZStack{
ForEach(dots, id: .self){ dot in
Circle()
.frame(width: 5, height: 5)
.position(x: dot.x, y: dot.y)
Path { path in
path.move(to: CGPoint(x: lastx, y: lasty))
path.addLine(to: CGPoint(x: dot.x, y: dot.y))
}.stroke(.green, lineWidth: 5)
}
}
Spacer()
Button {
let randx = CGFloat.random(in: 100...300)
let randy = CGFloat.random(in: 100...300)
dots.append(Dot(x: randx, y: randy))
lastx = randx
lasty = randy
} label: {
Text("Button")
}
}
}
}
2
Answers
Here I only maintain 1 path, and append to it each time rather than more than 1 path in the ForEach
You might want something a little nicer looking like
The problem is that with this loop:
you are creating multiple line segments by moving to the same point, and then adding a line to a different point.
What you want to do is:
Take a look at the difference here: