如何在带有动画的SwiftUI中移动对象?

时间:2020-05-02 00:45:44

标签: object animation swiftui

我想在屏幕上移动对象,使用户难以点击。

该对象将出现几秒钟,如果单击该对象将为用户提供游戏优势。

我不希望它出现在一个位置,然后再出现在另一个位置。我希望它可以从一个地方滑到另一个地方。

我的示例代码如下:

struct level1: View {

@State var makeIt10xPressed = false

@State var showWin10x = false

var timeTimer : Timer {
Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
    print("timer")
    self.showWin10x = true
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
        self.showWin10x = false
       }
    }
}

func makeIt10x () {
    if makeIt10xPressed == true {
        print("10x more point")

    }
}

func win10x () {

    self.makeIt10xPressed = true
 DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
     self.makeIt10xPressed = false
    }

}


var body: some View {
    GeometryReader { geometryProxy in
                ZStack {

Image("mine1")
          .resizable()
          .frame(width: UIScreen.main.bounds.height * 1.4, height: UIScreen.main.bounds.height)
          .gesture(DragGesture(minimumDistance: 0).onEnded { value in
          print("get one point")
                        })

if self.showWin10x {
                            Button(action: {
                            self.win10x()
                            }) {
                           Image("bat").resizable.frame(width: UIScreen.main.bounds.height * 0.10 , height: UIScreen.main.bounds.height * 0.10)
                            }
                            }

}

}.edgesIgnoringSafeArea(.all).onAppear() {


                 _ = self.timeTimer
}
}
}

我希望Image(“ bat”)在屏幕上移动。谢谢。

1 个答案:

答案 0 :(得分:1)

这是一个快速演示如何实现目标的方法;

我随机更改了View的偏移量,因此可以自由旅行

struct DemoView: View {

    let timer = Timer.publish(
        every: 1,       // Second
        tolerance: 0.1, // Gives tolerance so that SwiftUI makes optimization
        on: .main,      // Main Thread
        in: .common     // Common Loop
    ).autoconnect()

    @State var offset: CGSize = .zero

    var body: some View {
        VStack {
            Rectangle()
                .frame(width: 100, height: 100, alignment: .center)
                .offset(offset)
        }.onReceive(timer) { (_) in
            let widthBound = UIScreen.main.bounds.width / 2
            let heightBound = UIScreen.main.bounds.height / 2
            let randomOffset = CGSize(
                width: CGFloat.random(in: -widthBound...widthBound),
                height: CGFloat.random(in: -heightBound...heightBound)
            )
            withAnimation {
                self.offset = randomOffset
            }
        }
    }
}

enter image description here

您可以按照自己的需要玩游戏。