본문 바로가기
PROGRAMMING CODE/SWIFT

[SwiftUI] UI요소 랜덤위치로 바꾸기 (쥐잡기게임, Timer)

by daye_ 2023. 8. 17.


 

1초로 지정해놨는데 트랙패드로 쥐 잡기는 생각보다 어려웠음 ㅋ,ㅋ


import SwiftUI

struct CatchView: View {
    @State private var buttonPosition: CGPoint = CGPoint(x: 150, y: 150)
    @State var score : Int = 0
    
    var body: some View {
        VStack {
            Spacer()
            Text("score : \(score)")
            Button("🐹") {
                self.randomButtonPosition() //버튼을 눌러 쥐를 잡게되면 새로운 포지션으로 이동
                score += 1 //잡았을때 스코어
            }
            .position(buttonPosition) //쥐의 포지션
            
            Spacer()
        }
        .onAppear { //타이머를 지정해 매 순간 위치가 바뀌도록 지정
            let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
                self.randomButtonPosition()
            }
        }
    }
    
    func randomButtonPosition() { //랜덤 포지션 설정하는 함수
        let maxWidth = UIScreen.main.bounds.width
        let maxHeight = UIScreen.main.bounds.height
        
        let newX = CGFloat.random(in: 0...(maxWidth - 50)) //버튼 크기만큼 넓이도 띄워줌
        let newY = CGFloat.random(in: 0...(maxHeight - 100)) //score표시 요소 띄어주기
        
        buttonPosition = CGPoint(x: newX, y: newY) //포지션 재설정
    }
}

struct CatchView_Previews: PreviewProvider {
    static var previews: some View {
        CatchView(team: "Red")
    }
}

Timer.scheduledTimer

 

withTimeInterval :  초단위. 타이머 설정

reapets :  값을 false로 주면 타이머 중단 


랜덤포지션 + 이전에 그렸던 Path를 이용하면 팡파레 효과도 만들 수 있을것같음! 

메모메모