2022年7月

CoreMotion




import SpriteKit
import CoreMotion

enum CollisionTypes: UInt32 {
  case player = 1
  case wall = 2
  case star = 4
  case rig = 3
}

final class GameScene: SKScene, SKPhysicsContactDelegate {
 private var player: SKSpriteNode!
 private var lastTouchPosition: CGPoint?
 private var motionManager: CMMotionManager?
 private var scoreLabel: SKLabelNode!
 private var score = 0 {
  didSet {
      scoreLabel.text = "Score: \(score)"
    }
  }
private var isGameOver = false
private var items = [String]()
private var teleportDestination = [CGPoint]()

override func didMove(to view: SKView) {
   createScoreLabel()
   loadLevel()
   createPlayer()
   physicsWorld.gravity = .zero
   physicsWorld.contactDelegate = self
  motionManager = CMMotionManager()
  motionManager?.startAccelerometerUpdates()
  let rightRect = CGRect(x: self.frame.size.width, y: 0, width: 1, height: self.frame.size.height)
  let right = SKNode()
  right.physicsBody = SKPhysicsBody(edgeLoopFrom: rightRect)
  self.addChild(right)
  right.name = "right"
   // right.physicsBody?.categoryBitMask = rightCategory
  right.physicsBody?.categoryBitMask = CollisionTypes.rig.rawValue
   right.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
    right.physicsBody?.collisionBitMask = CollisionTypes.wall.rawValue
}

 override func update(_ currentTime: TimeInterval) {
  guard isGameOver == false else { return }
   #if targetEnvironment(simulator)
   if let lastTouchPosition = lastTouchPosition {
  let diff = CGPoint(x: lastTouchPosition.x - player.position.x, y: lastTouchPosition.y - player.position.y)
  physicsWorld.gravity = CGVector(dx: diff.x / 100, dy: diff.y / 100)
 }
 #else
  if let accelrometerData = motionManager?.accelerometerData {
   physicsWorld.gravity = CGVector(dx: accelrometerData.acceleration.x * 10, dy: accelrometerData.acceleration.y * 10)
 }
 #endif
/*
 if let accelerometerData = motionManager.accelerometerData {
 physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.y * -50, dy: accelerometerData.acceleration.x * 50)
 }
if let lastTouchPosition = lastTouchPosition {
 let diff = CGPoint(x: lastTouchPosition.x - player.position.x, y: lastTouchPosition.y - player.position.y)
   physicsWorld.gravity = CGVector(dx: diff.x / 200, dy: diff.y / 200)
}
 */
}
private func loadLevel() {
  let itm:CGFloat = frame.size.width/12
  guard let levelURL = Bundle.main.url(forResource: "level1", withExtension: "txt") else {
   fatalError("Could't find")
 }
guard let levelString = try? String(contentsOf: levelURL) else {
   fatalError("Could't load")
 }
 let lines = levelString.components(separatedBy: "\n")
  for (row, line) in lines.reversed().enumerated() {
    for (column, letter) in line.enumerated() {
     let position = CGPoint(x: (Int(itm) * column) + 16, y: (Int(itm) * row) + Int(self.frame.height) / 8)
     if letter == "a" {
     createBlock(in: position)
   }else if letter == "s" {
      createStar(in: position)
    }else if letter == "y" {
    createfild(in: position)
 }
 }
 }
}
private func createBlock(in position: CGPoint) {
  let node = SKSpriteNode(imageNamed: "Field0")
 node.name = "block"
  items.append(node.name!)
  node.position = position
  node.physicsBody = SKPhysicsBody(rectangleOf: node.size)
  node.physicsBody?.categoryBitMask = CollisionTypes.wall.rawValue
  node.physicsBody?.isDynamic = false
 addChild(node)
 node.setScale(1.05)
}
private func createScoreLabel() {
 scoreLabel = SKLabelNode(fontNamed: "AvenirNext-Bold")
  scoreLabel.text = "Score: 0"
  scoreLabel.horizontalAlignmentMode = .left
  scoreLabel.position = CGPoint(x: 50, y: 50)
  scoreLabel.zPosition = 2
  addChild(scoreLabel)
}
private func createPlayer() {
player = SKSpriteNode(imageNamed: "player")
 player.position = CGPoint(x: frame.size.width/12 + player.size.width * 0.38, y: frame.height - 270 )
 player.zPosition = 1
 player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
 player.physicsBody?.allowsRotation = false
 player.physicsBody?.linearDamping = 0.8
 player.physicsBody?.categoryBitMask = CollisionTypes.player.rawValue
 player.physicsBody?.contactTestBitMask = CollisionTypes.star.rawValue
 player.physicsBody?.collisionBitMask = CollisionTypes.wall.rawValue
addChild(player)
 player.setScale(0.55)
}
 private func createStar(in position: CGPoint) {
   let node = SKSpriteNode(imageNamed: "star")
  node.name = "star"
  items.append(node.name!)
  node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2)
  node.physicsBody?.isDynamic = false
  node.physicsBody?.categoryBitMask = CollisionTypes.star.rawValue
  node.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
  node.physicsBody?.collisionBitMask = 0
  node.position = position
  addChild(node)
  node.setScale(0.5)
 }
private func createfild(in position: CGPoint) {
  let node = SKSpriteNode(imageNamed: "Field2")
  node.name = "fild"
  items.append(node.name!)
  node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2)
  node.physicsBody?.isDynamic = false
  node.physicsBody?.categoryBitMask = CollisionTypes.rig.rawValue
 node.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
  node.physicsBody?.collisionBitMask = 0
  node.position = position
 addChild(node)
  node.setScale(1.01)
 }
private func playerCollided(with node: SKNode) {
  if node.name == "star" {
    node.removeFromParent()
    score += 1
}
  if node.name == "fild" {
    node.removeFromParent()
    score += 3
  }
 }
 private func ballCollided(with node: SKNode) {
  if node.name == "right" {
   node.removeFromParent()
   let gameOverScene = GameScene(size: self.frame.size)
   self.view?.presentScene(gameOverScene)
 }
}
func didBegin(_ contact: SKPhysicsContact) {
 guard let nodeA = contact.bodyA.node else { return }
 guard let nodeB = contact.bodyB.node else { return }
  if nodeA == player {
     playerCollided(with: nodeB)
 } else if nodeB == player {
    playerCollided(with: nodeA)
    ballCollided(with: nodeA)
 }
 }
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
 guard let touch = touches.first else { return }
  let location = touch.location(in: self)
  lastTouchPosition = location
 }
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
   guard let touch = touches.first else { return }
   let location = touch.location(in: self)
   lastTouchPosition = location
}
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
  lastTouchPosition = nil
  }
}

Collision


import UIKit
import SpriteKit


enum CollisionTypes: UInt32 {
    case player = 1
    case wall = 2
    case star = 4
    case vortex = 8
    case finish = 16
}

class GameScene: SKScene, SKPhysicsContactDelegate {
 var player: SKSpriteNode!
 var block: SKSpriteNode!
 var vortex: SKSpriteNode!
 var star: SKSpriteNode!
 var finish: SKSpriteNode!
 var ball: SKShapeNode!
 var isGameOver = false

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)

ball = SKShapeNode(circleOfRadius: 10) //circleOfRadiusで円の半径
ball.position = CGPoint(x:self.frame.midX, y:self.frame.midY+200)
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?.applyImpulse(CGVector(dx: 40, dy: 40))
ball.physicsBody?.affectedByGravity = false
ball.physicsBody?.isDynamic = false
ball.physicsBody?.friction = 0
ball.physicsBody?.restitution = 1
ball.name = "ball"
ball.physicsBody?.collisionBitMask = 0
// ball.physicsBody?.categoryBitMask = CollisionTypes.wall.rawValue
//  ball.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue

block = SKSpriteNode(imageNamed: "block")
block.position = CGPoint(x: 70, y: 200)
block.physicsBody = SKPhysicsBody(rectangleOf: block.size)
//  block.physicsBody?.categoryBitMask = CollisionTypes.wall.rawValue
//  block.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
block.physicsBody?.collisionBitMask = 0
block.physicsBody?.isDynamic = false
block.name = "block"
addChild(block)

vortex = SKSpriteNode(imageNamed: "vortex")
vortex.name = "vortex"
vortex.position = CGPoint(x: 150, y: 200)
vortex.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat.pi, duration: 1)))
vortex.physicsBody = SKPhysicsBody(circleOfRadius: vortex.size.width / 2)
vortex.physicsBody?.isDynamic = false
//  vortex.physicsBody?.categoryBitMask = CollisionTypes.vortex.rawValue
// vortex.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
//  vortex.physicsBody?.collisionBitMask = 0
addChild(vortex)

star = SKSpriteNode(imageNamed: "star")
star.physicsBody = SKPhysicsBody(circleOfRadius: star.size.width / 2)
star.name = "star"
star.position = CGPoint(x: 220, y: 200)
star.physicsBody?.isDynamic = false
//  star.physicsBody?.categoryBitMask = CollisionTypes.star.rawValue
//  star.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
//  star.physicsBody?.collisionBitMask = 0
addChild(star)

finish = SKSpriteNode(imageNamed: "finish")
finish.name = "finish"
finish.position = CGPoint(x: 300, y: 200)
finish.physicsBody = SKPhysicsBody(circleOfRadius: finish.size.width / 2)
finish.physicsBody?.isDynamic = false
//  finish.physicsBody?.categoryBitMask = CollisionTypes.finish.rawValue
//  finish.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
//  finish.physicsBody?.collisionBitMask = 0
addChild(finish)

player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 96, y: 572)
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
player.physicsBody?.allowsRotation = false
player.physicsBody?.linearDamping = 0.5
player.physicsBody?.categoryBitMask = CollisionTypes.player.rawValue
player.physicsBody?.contactTestBitMask = CollisionTypes.finish.rawValue
//  player.physicsBody?.contactTestBitMask = CollisionTypes.star.rawValue | CollisionTypes.vortex.rawValue | CollisionTypes.finish.rawValue | CollisionTypes.wall.rawValue
// player.physicsBody?.collisionBitMask = CollisionTypes.wall.rawValue
player.physicsBody?.collisionBitMask = 0
 addChild(player)
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
    for touches : AnyObject in touches{
    // タッチした点を得る.
     let location = touches.location(in: self)
     //   circle.position = location
     // 移動時間を1秒に指定しています。
     let travelTime = SKAction.move(to: location, duration: 1)
     player.run(travelTime)
  }
 }
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
   // Stop node from moving to touch
  //   touched = false
 }

func didBegin(_ contact: SKPhysicsContact) {
    guard let nodeA = contact.bodyA.node else { return }
    guard let nodeB = contact.bodyB.node else { return }
      if nodeA == player {
         playerCollided(with: contact.bodyB.node!)
    } else if nodeB == player {
         playerCollided(with: contact.bodyA.node!)
   }
}

func playerCollided(with node: SKNode) {
   if node.name == "vortex" {
    player.physicsBody?.isDynamic = false
 //   if isGameOver == true {
 //  starfield.removeFromParent()
 //   sprite.removeFromParent()
 //   }
  //   isGameOver = true
 //   score -= 1
 //   let move = SKAction.move(to: node.position, duration: 0.25)
 let fade = SKAction.fadeAlpha(to: 0.5, duration: 1)
//    let scale = SKAction.scale(to: 0.01, duration: 1)
 //   let scale2 = SKAction.scale(to: 1, duration: 1)
//    let remove = SKAction.removeFromParent()
//   let sequence = SKAction.sequence([move, scale, scale2])
//   let moveRepeat = SKAction.repeatForever(sequence)
  player.run(fade, withKey:"moving")
  player.removeFromParent()
 //   if let action = player.action(forKey: "moving") {
 //  action.speed = 1
  //  }
let scene = GameScene2(size: self.frame.size)
    let transition = SKTransition.moveIn(with: SKTransitionDirection.right, duration: 1.5)
   self.view?.presentScene(scene, transition: transition)
 } else if node.name == "star" {
      node.removeFromParent()
 //   score += 1
  } else if node.name == "finish" {
  let move = SKAction.move(to: node.position, duration: 0.25)
  let scale = SKAction.scale(to: 0.01, duration: 1)
  let remove = SKAction.removeFromParent()
 let sequence = SKAction.sequence([move, scale, remove])
  node.run(sequence, withKey:"moving")
   //    node.setScale(1.6)
   //    node.removeFromParent()
    } else if node.name == "block" {
    //  node.removeFromParent()
 }
    else if node.name == "ball" {
  //  node.removeFromParent()
     ball.fillColor = UIColor.blue
      node.alpha = 0.6
      node.setScale(5.0)
     }
 }
override func update(_ currentTime: TimeInterval) {
  //   if !isGameOver{
   //    score += 1
  //      }
  }
}

Timer


import UIKit
import SpriteKit


class GameScene: SKScene, SKPhysicsContactDelegate {
 var toggle:Bool = true
  var lastUpdateTime : TimeInterval = 0
  var label: SKLabelNode!
  var myTimer = Timer()
  let timeLabel  = SKLabelNode(fontNamed: "Verdana-bold")
  var timeCount = 10

  override func didMove(to view: SKView) {
  backgroundColor = .yellow
  self.physicsWorld.contactDelegate = self
  self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
  physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)
  let ball = SKShapeNode(circleOfRadius: 40) //circleOfRadiusで円の半径
  ball.position = CGPoint(x:self.frame.midX, y:self.frame.midY+100)
  ball.fillColor = UIColor.white
  ball.lineWidth = 0.0
  ball.strokeColor = UIColor.red
  ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width/2)
  self.addChild(ball)
  //ボールの飛んでいく方向
  ball.physicsBody?.applyImpulse(CGVector(dx: 40, dy: 40))
  ball.physicsBody?.affectedByGravity = false
  ball.physicsBody?.isDynamic = true
  ball.physicsBody?.friction = 0
  ball.physicsBody?.restitution = 1

timeLabel.text = "Count:\(timeCount)"
    //timeLabelが動かないようにleft固定
    //  timeLabel.horizontalAlignmentMode = .left
    timeLabel.fontSize = 50
    timeLabel.fontColor = SKColor.black
  timeLabel.position = CGPoint(x: self.frame.midX, y: self.frame.midY )
    self.addChild(timeLabel)
    // タイマーをスタートする(1.0秒ごとにtimerUpdateを繰り返し実行)
  myTimer = Timer.scheduledTimer(
     timeInterval: 1.0,
     target: self,
     selector: #selector(timerUpdate),
     userInfo: nil,
     repeats: true)
}

@objc func timerUpdate() {
   timeCount -= 1
   timeLabel.text = "Count:\(timeCount)"
if timeCount < 0 {
 myTimer.invalidate()
 self.timeLabel.isHidden = true
  // let scene = GameScene2(size: self.frame.size)
 //  let transition = SKTransition.moveIn(with: SKTransitionDirection.right, duration: 1.5)
 //  self.view?.presentScene(scene, transition: transition)
    let scene = GameScene2(size: self.frame.size)
    scene.scaleMode = scaleMode
    self.view!.presentScene(scene, transition: .doorsCloseVertical(withDuration: 0.8))    
   }
}
    
func fireTimer() {
    let date:Date = Date()
    let format = DateFormatter()
   format.dateFormat = "yyyy/MM/dd HH:mm:ss"
   let sDate = format.string(from: date)
    label = SKLabelNode(fontNamed: "Avenir-Black")
    label.text = sDate
    label.position = CGPoint(x: self.frame.midX, y: self.frame.midY + 50)
    label.fontSize = 20
    label.fontColor = SKColor.blue
    self.addChild(label)
 }
func toggleTest() {
   if(toggle){
 fireTimer()
   toggle = false;
 }else{
   label.removeFromParent()
   toggle = true;
 }
}
    
override func update(_ currentTime: TimeInterval) {
  if (lastUpdateTime == 0) {
  self.lastUpdateTime = currentTime - 0.5
   }
  if (currentTime - lastUpdateTime > 1) {
    toggleTest()
    lastUpdateTime = currentTime - 0.5
  }
}
}