Hello everyone! Can I attach an object with a magnete animation to the other in SwiftUI?
Please show me that with a simple example.
Thank you in advance.
Hello everyone! Can I attach an object with a magnete animation to the other in SwiftUI?
Please show me that with a simple example.
Thank you in advance.
Could you show the present code, without magnet effect ?
What exact effect do you want ?
Then you will have to define a profile to mimic magnetic effect.
knowing that force is proportional to 1/ d3 (cube of distance), you can compute the speed. Or more simply, have a speed that grow very rapidly when magnets get closer.
Here's the code:
import PlaygroundSupport
import SwiftUI
struct ContentView: View {
@State private var isDragging = false
@State private var dragOffset: CGSize = .zero
@State var position: CGSize = .zero
@State private var hovered = false
var body: some View {
RoundedRectangle(cornerRadius: 20)
.foregroundColor(.red)
.frame(width: 100, height: 100)
.position(x: 400, y: 350)
RoundedRectangle(cornerRadius: 20)
.foregroundColor(.blue)
.frame(width: 100, height: 100)
.position(x: 400, y: 350)
.animation(.default, value: hovered)
.offset(x: dragOffset.width + position.width, y: dragOffset.height + position.height)
.gesture(
DragGesture()
.onChanged({ value in
self.dragOffset = value.translation
})
.onEnded({ value in
self.position.width += value.translation.width
self.position.height += value.translation.height
self.dragOffset = .zero
})
)
}
}
PlaygroundPage.current.setLiveView(ContentView())
I want the blue square to attach with the red square when I drag near it.