我想在SwiftUI中写一个简单的游戏,用户可以拖动一个圆圈来躲避树木,它应该绘制一个轨迹,但是轨迹非常奇怪,是矩形而不是平滑的曲线.有人能帮我吗?
以下是我的代码:
import SwiftUI
struct ContentView: View {
@State private var track = [CGFloat]()
@State private var offset: CGFloat = 0
let timer = Timer.publish(every: 0.001, on: .current, in: .common).autoconnect()
var body: some View {
GeometryReader { geo in
ZStack {
Color.black
Path { path in
let height = (geo.size.height / 2) / CGFloat(track.count)
for i in 0..<track.count {
path.addLine(to: CGPoint(x: geo.size.width * track[i], y: height * CGFloat(i)))
path.move(to: CGPoint(x: geo.size.width * track[i], y: height * CGFloat(i)))
}
} .stroke(lineWidth: 1)
.foregroundStyle(.yellow)
Circle()
.frame(width: 25)
.foregroundStyle(.red)
.position(x: offset, y: geo.size.height / 2)
.gesture (
DragGesture()
.onChanged { value in
offset = min(geo.size.width - 15, max(15 ,value.location.x))
}
)
.onAppear {
offset = geo.size.width / 2
}
.onReceive(timer, perform: { _ in
track.append((offset / geo.size.width))
if track.count >= 100 {
track.removeFirst()
}
})
}
}
}
}