• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Spritekit

My WordPress site

  • Top
  • SpriteKitBase
    • Collision
    • Enumerated
    • Shooting
    • Breakout
    • Physics1
      • physics4
      • physics3
      • Physics2
  • SwiftUI&SpriteKit
    • TabScroll
    • LocalWebView
      • Counter
      • StateObject
      • Button
      • SceneMove
    • Swift Learning
  • Photo Gallery
    • Photo Galler 2
    • Photo Gallery 3
    • リンク
      • プロフィール
      • p5.play test

Counter

04/03/2022 by kyougif


import SwiftUI
import SpriteKit

struct ContentView: View {
@ObservedObject var counter = Counter()
var scene: SKScene {
let scene = GameScene()
scene.counter = counter
scene.size = CGSize(width: 300, height: 400)
scene.scaleMode = .fill
return scene
}
var body: some View {
VStack{
SpriteView(scene: scene)
.frame(width: 300, height: 400)
.ignoresSafeArea()
//   Button{
//  counter.add(count: 1)
//     counter.reset()
//   } label: {
//       Text("reset to count")
//    }
Text("New count = \(counter.count)")
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
/////////////////////////////////
Counter.swift

import SwiftUI
class Counter: ObservableObject {
@Published var count : Int = 0
func add(count: Int) {
    self.count += count
 //   print("Add \(count); new total: \(self.count)")
 }
 func reset() { count = 0 }
}
//////////////////////////
GameScene.swift

import SwiftUI
import SpriteKit
class GameScene: SKScene {
    var counter : Counter?
    var count = 0   
 override func didMove(to view: SKView) {
        physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
    guard let touch = touches.first else { return }
    let location = touch.location(in: self)
    let box = SKSpriteNode(color: SKColor.red, size: CGSize(width: 50, height: 50))
    box.position = location
    box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50, height: 50))
        self.addChild(box)
    // score += 1
    //  counter.add(count: 1)
        counter?.add(count: 1)
    }
}

Filed Under: Programming, spritekit, swiftui

Primary Sidebar

最近の投稿

  • ObservableObj
  • SideMenu
  • TabScroll
  • Text
  • TappedNodes
  • Collision2
  • CoreMotion
  • Collision
  • Timer
  • Enumerated
  • Random
  • SwiftUI-List
  • Shooting
  • Sound
  • Camera
  • SpriteSheet
  • SKPhysics42
  • physics4
  • physics3
  • Physics2

アーカイブ

  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2014年9月
  • 2014年5月

カテゴリー

  • Programming
  • spritekit
  • swiftui

固定ページ

  • Home
  • p5.play test
  • Photo Galler 2
  • Photo Gallery
  • Photo Gallery 3
  • Top
  • プロフィール
  • リンク

Copyright © 2026 · Genesis-child on Genesis Framework · WordPress · Log in