0

I want to move an object on the screen, making it harder for the user to click on.

The object will appear for a few seconds and if clicked it will provide user an advantage in the game.

I wouldn't want it to appear in one spot then a second later appear on another spot. I'd love it to slide from place to another.

My example code is below:

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 } } } 

I want the Image("bat") to move around the screen. Thanks.

1 Answer 1

3

Here is a quick demo how you might achieve your goal;

I randomly changed the View's offset, so it is free to travel

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

You can play with the bounds to fit your needs.

Sign up to request clarification or add additional context in comments.

3 Comments

Amazing, but when I implemented this to my code, unlike your demo, the object moves a few times then stops moving. How can I fix it?
Make sure the Timer is alive?
I thought it would stay alive because there's "in: .common". Even when I call timer in another timer that on repeat, the object doesn't move after the initial movements.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.