• 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

Archives for 4月 2022

Breakout

04/10/2022 by kyougif

表示するフォントのサイズを引数で指定します。
標準で使える定義済フォントサイズには次のようなものがあります。


GameScene
import SpriteKit
import GameplayKit


class GameScene: SKScene, SKPhysicsContactDelegate {

let kBlockWidth             : CGFloat = 55.0
let kBlockHeight            : CGFloat = 25.0
let kBlockRows              : Int = 8
let kBlockColumns           : Int = 7
var kBlockRecoverTime = 10.0

let ballCategoryName = "ball"
let paddleCategoryName = "paddle"
let blockCategoryName = "block"

let ballCategory:UInt32 = 0x1 << 0
let bottomCategory:UInt32 = 0x1 << 1
let blockCategory:UInt32 = 0x1 << 2
let paddleCategory:UInt32 = 0x1 << 3

var label = SKLabelNode(fontNamed: "HelveticaNeue-Light")
var score = 0
let paddle = SKShapeNode(rectOf: CGSize(width:110, height:25),cornerRadius: 2)

override func didMove(to view: SKView) {
backgroundColor = .white
self.physicsWorld.contactDelegate = self
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)

let ball = SKShapeNode(circleOfRadius: 12)//circleOfRadiusで円の半径
ball.position = CGPoint(x:self.frame.midX, y:self.frame.midY-100)
ball.fillColor = UIColor.red
ball.lineWidth = 0.0
ball.strokeColor = UIColor.red

ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width/2)
self.addChild(ball)
//ボールの飛んでいく方向
ball.physicsBody?.friction = 0
ball.physicsBody?.restitution = 1
ball.physicsBody?.linearDamping = 0
ball.physicsBody?.allowsRotation = false
ball.physicsBody?.applyImpulse(CGVector(dx: 5, dy: 5))

// 四角形を作成
paddle.position = CGPoint(x:self.frame.midX, y:self.frame.midY-360)
paddle.name = paddleCategoryName
paddle.fillColor = .green
paddle.lineWidth = 0.0
paddle.physicsBody = SKPhysicsBody(rectangleOf: paddle.frame.size)
paddle.physicsBody?.restitution = 0.1
paddle.physicsBody?.friction = 0.2
paddle.physicsBody?.linearDamping = 0
paddle.physicsBody?.isDynamic = false
self.addChild(paddle)

let totalBlocksWidth = kBlockWidth * CGFloat(kBlockColumns)
let xOffset = (frame.width - totalBlocksWidth) / 2
let yOffset = frame.height * 0.6
for i in 0.., with event: UIEvent?) {
// for touch in touches
// {
// let toucLocation = touch.location(in: self)
// border.position.x = toucLocation.x
// }
}

//パドル
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
for touch in touches
{
let toucLocation = touch.location(in: self)
paddle.position.x = toucLocation.x
}
}

func didBegin(_ contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()

if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask{
firstBody = contact.bodyA
secondBody = contact.bodyB
}else{
firstBody = contact.bodyB
secondBody = contact.bodyA
}

if firstBody.categoryBitMask == ballCategory && secondBody.categoryBitMask == bottomCategory{
//  let changeSceneAction = SKAction.run(changeScene)
//  self.run(changeSceneAction)
let gameOverScene = GameOverScene(size: self.frame.size)
self.view?.presentScene(gameOverScene)
}
if firstBody.categoryBitMask == ballCategory && secondBody.categoryBitMask == blockCategory{
secondBody.node?.removeFromParent()
score += 1
label.text = "\(score)"
if score >= 12 {
let gameOverScene = GameClearScene(size: self.frame.size)
self.view?.presentScene(gameOverScene)
}
}
}
/*
func changeScene(){
let sceneToMoveTo = GameOverScene(size: self.frame.size)
sceneToMoveTo.scaleMode = self.scaleMode
let myTransition = SKTransition.fade(withDuration: 0.5)
self.view!.presentScene(sceneToMoveTo, transition: myTransition)
}
*/
}

///////////////////////////////////
GameOverScene.swift

import SpriteKit

class GameOverScene: SKScene {

override func didMove(to view: SKView) {
backgroundColor = .blue

let gameOverLabel = SKLabelNode(fontNamed: "Avenir-Black")
gameOverLabel.fontSize = 46
gameOverLabel.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
gameOverLabel.text = "GAME OVER!"
self.addChild(gameOverLabel)
}

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
let breakOutGameScene = GameScene(size: self.size)
self.view?.presentScene(breakOutGameScene)
}
}
/////////////////////////////
GameClearScene.swift

import SpriteKit
class GameClearScene: SKScene {
override func didMove(to view: SKView) {
backgroundColor = .green
let gameOverLabel = SKLabelNode(fontNamed: "Avenir-Black")
gameOverLabel.fontSize = 46
gameOverLabel.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
gameOverLabel.text = "GAME CLEAR!"
self.addChild(gameOverLabel)
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
let breakOutGameScene = GameScene(size: self.size)
self.view?.presentScene(breakOutGameScene)
}
}

Filed Under: Programming, spritekit

Button

04/10/2022 by kyougif


GameScene
import SpriteKit
import GameplayKit

class GameScene: SKScene {
  let label = SKLabelNode(fontNamed: "HelveticaNeue-Light")
  let button = SKSpriteNode(imageNamed: "blue2.png")

    override func didMove(to view: SKView) {
      physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
      self.backgroundColor = .green

       label.text = "Hello World!"
       label.position = CGPoint(x: self.frame.midX, y: self.frame.midY + 10)
       label.fontSize = 20
       label.fontColor = SKColor.white
      self.addChild(label)

       button.position = CGPoint(x: size.width/2, y: size.height/2+120)
       button.zPosition = 1
       button.name = "button"
       button.setScale(0.4)
       self.addChild(button)
        button.run(SKAction.scale(to: 0.5, duration: 0.3))
       button.alpha = 1

    }
    override func touchesEnded(_ touches: Set, with event: UIEvent?) {
        button.alpha = 1
        button.setScale(0.5)
    }

    override func touchesBegan(_ touches: Set, with event: UIEvent?){
        for touch in touches {
          let location = touch.location(in: self)
          let touchedNode = atPoint(location)

          if touchedNode.name == "button" {
              button.alpha = 0.5
              button.setScale(0.6)
              if label.fontSize < 50 {
              label.fontSize += 2
              }
              else{
              label.fontSize = 20
             }
         }
         
      }
    }
}
//////////////////////////
ContentView.swift
import SwiftUI
import SpriteKit

struct ContentView: View {
    let screenWidth  = UIScreen.main.bounds.width
    let screenHeight = UIScreen.main.bounds.height
    var scene: SKScene {
        let scene = GameScene()
        scene.size = CGSize(width: screenWidth, height: screenHeight)
        scene.scaleMode = .fill
        return scene
    }
    var body: some View {
        SpriteView(scene: scene)
          .frame(width: screenWidth, height: screenHeight)
          .ignoresSafeArea()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

//////////////////////////
ButtonApp.swift

import SwiftUI
@main
struct ButtonApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Filed Under: Programming, spritekit

SceneMove

04/10/2022 by kyougif


GameScene

import SpriteKit
import GameplayKit
import SwiftUI

class GameScene: SKScene, SKPhysicsContactDelegate, ObservableObject {  

    @Published var gameScore = 0
        override func didMove(to view: SKView) {
        backgroundColor = .yellow
        physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
        ball()
     //   addScore()
    }
    func ball() {
           let ball = SKShapeNode(circleOfRadius: 50)
           ball.position = CGPoint(x: 100, y: 100)
           ball.fillColor = .blue
           self.addChild(ball)
       }

    let removeLabel = SKAction.sequence([SKAction.fadeIn(withDuration: 0.3),
    SKAction.wait(forDuration: 0.8), SKAction.fadeOut(withDuration: 0.3)])

    override func sceneDidLoad() {
        super.sceneDidLoad()
    }
   func addScore(){
        if gameScore < 10 {
            gameScore += 2          
        } else {
            gameScore += 4         
        }
    }    
}

/////////////
GameScene2

import SpriteKit
import GameplayKit

class GameScene2: SKScene {
    override func didMove(to view: SKView) {
        backgroundColor = .blue
        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: 40, height: 40))
        box.position = location
        box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 40, height: 40))
        addChild(box)
    }
}
/////////////////////
ContentView

import SwiftUI
import SpriteKit

struct ContentView: View {
@State var switcher = false
    @StateObject var gameScene: GameScene = GameScene() // <<: Here 3

var scene: SKScene {
    let scene = GameScene()
       scene.size = CGSize(width: 216, height: 216)
       scene.scaleMode = .fill
    //    scene.backgroundColor = .yellow
       return scene
}
var scene2: SKScene {
    let scene2 = GameScene2()
       scene2.size = CGSize(width: 216, height: 216)
       scene2.scaleMode = .fill
       return scene2
}

var body: some View {    
 //   Text("Score: \(gameScene.gameScore)") // <<: Here 4
      //       .onTapGesture {
     //            gameScene.addScore()  // <<: Here 5
    //         }
    Button(action: {
        gameScene.addScore()
         }, label: {
             Text("Score: \(gameScene.gameScore)")
         })
  if switcher {
    SpriteView(scene: scene)
        .frame(width: 256, height: 256)
        .ignoresSafeArea()
        .background(Color.red)
        .onAppear {
          scene2.isPaused = true
        }
        .onDisappear {
          scene2.isPaused = false
        }
        
  } else {
    SpriteView(scene: scene2)
        .frame(width: 256, height: 256)
        .ignoresSafeArea()
        .background(Color.blue)
        .onAppear {
          scene.isPaused = true      
        }
        .onDisappear {
          scene.isPaused = false
        }  
  }
  Button {
    withAnimation(.easeInOut(duration: 1.0)) {
      switcher.toggle()
    }
  } label: {
    Text("SceneMove")
  }
}
}

Filed Under: Programming, spritekit, swiftui

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

StateObject

04/02/2022 by kyougif

@StateObjectと@ObservedObjectの違い
StateObjectCounterは親Viewのcounterが更新されても値を保持しているのに対し、
OvservedObjectCounterは親Viewの値更新に伴い値が初期化されている。
ライフサイクルが異なる。
@ObservedObjectは親Viewが再描画される度(= 親Viewのプロパティが更新される度)に更新され、保持するViewが再描画される。
counter (親View)
StateObjectCounter (子View)
OvservedObjectCounter (子View)


import SwiftUI


struct ContentView: View {
@State var counter = 0
var body: some View {
VStack(alignment: .leading, spacing: 30) {
HStack {
Text("counter: \(counter)")
Button("count up") {
counter += 1
}
}
StateObjectCounter()
ObservedObjectCounter()
}
}
}

final class Counter: ObservableObject {
@Published var number = 0
func increment() { number += 1 }
func reset() { number = 0 }
}

struct StateObjectCounter: View {
@StateObject private var counter = Counter()
var body: some View {
HStack {
Text("StateObject: \(counter.number)")
Button("count up") {
counter.number += 1
}
Button("Reset") {
self.counter.reset()
}
}
}
}

struct ObservedObjectCounter: View {
@ObservedObject private var counter = Counter()

var body: some View {
HStack {
Text("OvservedObject: \(counter.number)")
Button("count up") {
counter.number += 1
}
}
}
}

Filed Under: Programming, swiftui

SwiftUI&SpriteKit

04/02/2022 by kyougif


ContentView.swift

import SwiftUI
import SpriteKit
struct ContentView: View {
    var scene: SKScene {
        let scene = GameScene()
        scene.size = CGSize(width: 300, height: 400)
        scene.scaleMode = .fill
        return scene
    }

    var body: some View {
        SpriteView(scene: scene)
            .frame(width: 300, height: 400)
            .ignoresSafeArea()
    }
}
/*
struct ContentView: View {
let width = UIScreen.main.bounds.size.width
let height = UIScreen.main.bounds.size.height

var body: some View {
let scene = GameScene()
scene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
scene.scaleMode = .resizeFill
return SpriteView(scene: scene)
.frame(width: width, height: height)
.edgesIgnoringSafeArea(.all)
}
}
*/
/////////////////////
GameScene.swift

import SpriteKit
import GameplayKit
class GameScene: SKScene {
let width = UIScreen.main.bounds.size.width
let height = UIScreen.main.bounds.size.height
var shapeNode = SKShapeNode()
override func didMove(to view: SKView) {
backgroundColor = .blue
let rect = CGRect(x: -1 * width / 2,
y: -1 * height / 2,
width: width,
height: height);
self.physicsBody = SKPhysicsBody(edgeLoopFrom: rect)
physicsWorld.gravity = CGVector(dx: 0.0, dy: -1.0)
print("frame what?")
print(frame)
// 落下するボール
shapeNode = SKShapeNode(circleOfRadius: 50)
shapeNode.position = CGPoint(x: 0,
y: 150)
shapeNode.fillColor = .white
shapeNode.strokeColor = .blue
shapeNode.physicsBody = SKPhysicsBody(circleOfRadius: shapeNode.frame.width / 2)
shapeNode.physicsBody?.isDynamic = true
shapeNode.physicsBody?.linearDamping = 0.1
shapeNode.physicsBody?.restitution = 0.8
addChild(shapeNode)
// 動かないボール
let shapeNode3 = SKShapeNode(circleOfRadius: 50)
shapeNode3.position = CGPoint(x: 40, y: -90)
shapeNode3.fillColor = .red
shapeNode3.strokeColor = .red
shapeNode3.physicsBody = SKPhysicsBody(circleOfRadius: shapeNode.frame.width / 2)
shapeNode3.physicsBody?.isDynamic = false
shapeNode3.physicsBody?.affectedByGravity = false
addChild(shapeNode3)
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
shapeNode.physicsBody?.applyImpulse(CGVector(
dx: Double(arc4random_uniform(200)) - 100.0,
dy: Double(arc4random_uniform(200)) - 100.0))
}
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
}
}

Filed Under: Programming, swiftui

  • « Go to Previous Page
  • Go to page 1
  • Go to page 2
  • Go to page 3
  • Go to Next Page »

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