Spritekit
My WordPress site
My WordPress site
2022年6月
import UIKit
import SpriteKit
import Foundation
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 scoreLabel: SKLabelNode!
private var score = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
private var items = [String]()
private var teleportDestination = [CGPoint]()
override func didMove(to view: SKView) {
createScoreLabel()
loadLevel()
createPlayer()
physicsWorld.gravity = .zero
physicsWorld.contactDelegate = self
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 = CollisionTypes.rig.rawValue
right.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
right.physicsBody?.collisionBitMask = CollisionTypes.wall.rawValue
}
override func update(_ currentTime: TimeInterval) {
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: 16, y: 16)
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 - 70 )
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.star.rawValue
node.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
node.physicsBody?.collisionBitMask = 0
node.position = position
addChild(node)
node.setScale(1.05)
}
private func playerCollided(with node: SKNode) {
if node.name == "star" {
node.removeFromParent()
score += 1
}
}
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
}
}
///////
level1.txt
a aaaaaaaaay
a a
aaaaaaaa aaa
as a
a aa aayaaa
aaaaa sa
a aaaaaa
aaaaa aaaaaa
aaaaa aaaaaa
asaaa sa
a aaa aaaaaa
a yaaaaa
aaaaa
aaaaasaaaaaa
yaaaaaaaaaaa
//////
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
private let playerCategory: UInt32 = 0x1 << 0
private let enemyCategory: UInt32 = 0x1 << 1
private let beamCategory: UInt32 = 0x1 << 0
private let shipCategory: UInt32 = 0x1 << 1
private let rectCategory: UInt32 = 0x1 << 1
private let ballCategory: UInt32 = 0x1 << 1
var label = SKLabelNode(fontNamed: "HelveticaNeue-Light")
var label2 = SKLabelNode(fontNamed: "HelveticaNeue-Light")
var score = 5
var ship = SKSpriteNode()
var bullet : SKSpriteNode!
var bullet2 : SKSpriteNode!
var ball : SKShapeNode!
var touched:Bool = false
var lastUpdateTime2 : TimeInterval = 0
let red = CGFloat.random(in: 0...1)
let gr = CGFloat.random(in: 0...1)
et bl = CGFloat.random(in: 0...1)
let colors = [
SKColor.green, SKColor.red, SKColor.blue,
SKColor.magenta, SKColor.yellow, SKColor.brown,
SKColor.black, SKColor.orange, SKColor.purple, SKColor.lightGray
]
public func randomColor(opacity: CGFloat) -> UIColor {
let r: UInt32 = arc4random_uniform(255)
let g: UInt32 = arc4random_uniform(255)
let b: UInt32 = arc4random_uniform(255)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: opacity)
}
override func didMove(to view: SKView) {
backgroundColor = .blue
// backgroundColor = .white
self.physicsWorld.contactDelegate = self;
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
label.text = "0"
let labelSize: CGFloat = 60.0
label.fontSize = labelSize
label.position = CGPoint(x:self.frame.midX, y:self.frame.height-120)
label.fontColor = SKColor.black
self.addChild(label)
for _ in 0...5 {
let myrect = SKShapeNode(rectOf: CGSize(width:50, height:50),cornerRadius: 5)
myrect.position = CGPoint(x: Int.random(in: 100...300), y: Int.random(in: 200...500))
myrect.fillColor = randomColor(opacity: 1.0)
// myrect.fillColor = colors.randomElement()!
myrect.lineWidth = 0.0
myrect.physicsBody = SKPhysicsBody(rectangleOf:myrect.frame.size)
myrect.physicsBody?.affectedByGravity = false
myrect.physicsBody?.isDynamic = false
self.addChild(myrect)
myrect.physicsBody?.categoryBitMask = rectCategory
}
for j in 0...5 {
let color1 = UIColor(red: red*CGFloat(j), green: gr*CGFloat(j), blue: bl*CGFloat(j), alpha: 1)
let radius: CGFloat = 20
ball = SKShapeNode(circleOfRadius: radius)
let randIntX = CGFloat(Int.random(in : 0...300) + 50)
let randIntY = CGFloat(Int.random(in : 0...300) + 320)
ball.fillColor = color1
ball.position = CGPoint(x:randIntX, y:randIntY)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width / 2)
ball.physicsBody!.isDynamic = true
ball.physicsBody!.affectedByGravity = false
addChild( ball)
ball.name = "Ball"
ball.physicsBody?.categoryBitMask = ballCategory
}
shipstart()
label2.text = ""
label2.fontSize = 75
label2.position = CGPoint(x:self.frame.midX, y:self.frame.height-360)
label2.fontColor = SKColor.yellow
label2.name = "button"
self.addChild(label2)
}
func shipstart(){
ship = SKSpriteNode(imageNamed: "ship")
ship.position = CGPoint(x: self.frame.midX, y: frame.height / 11 )
addChild(self.ship)
ship.physicsBody = SKPhysicsBody(rectangleOf: ship.frame.size)
ship.physicsBody!.isDynamic = true
ship.physicsBody!.affectedByGravity = false
ship.physicsBody?.allowsRotation = false
ship.name = "ship"
ship.physicsBody?.categoryBitMask = playerCategory
// ship.physicsBody?.contactTestBitMask = enemyCategory
}
func shoot() {
bullet = SKSpriteNode(imageNamed: "beam")
// bullet.position = CGPoint(x: Int.random(in: 20...Int(self.frame.width) - 20), y: 100)
bullet.physicsBody = SKPhysicsBody(circleOfRadius: bullet.size.width/2)
bullet.physicsBody!.isDynamic = true
bullet.physicsBody!.affectedByGravity = false
bullet.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 0))
bullet.physicsBody?.allowsRotation = false
// bullet.physicsBody?.usesPreciseCollisionDetection = true
bullet.physicsBody = SKPhysicsBody(rectangleOf: bullet.size)
self.addChild(bullet)
bullet.name = "Bullet"
bullet.anchorPoint = CGPoint(x: 0.5, y: 0)
// 敵ビームスプライトの中央下側を原点とする
bullet.position = CGPoint(x: ship.position.x, y: ship.position.y + ship.size.height * 0.5)
// 敵スプライトの先端にビームを配置する
bullet.physicsBody?.categoryBitMask = playerCategory
bullet.physicsBody?.contactTestBitMask = enemyCategory
// ミサイルの発射位置の作成
// bullet.position = CGPoint(x: self.ship.position.x - 2, y: self.ship.position.y)
let move = SKAction.moveTo(y: frame.height, duration: 0.9)
let remove = SKAction.removeFromParent()
bullet.run(SKAction.sequence([move, remove]))
}
// teki
private func spawnEnemy() {
let enemy = SKSpriteNode(imageNamed: "enemy_ship")
enemy.anchorPoint = CGPoint(x: 0.5, y: 0.5)
enemy.position.x = size.width * (0.25 + CGFloat(arc4random_uniform(5)) / 10.0) // 敵の横方向の位置をシーン幅の1/4〜3/4の間の値にする
enemy.position.y = size.height + enemy.size.height * 0.5 // 敵の縦方向の位置をシーン上端にする
// enemy.zPosition = ship.zPosition + 10
// 敵スプライトをプレイヤーより前面に表示する
enemy.name = "enemy_ship"
enemy.physicsBody = SKPhysicsBody(rectangleOf: enemy.size)
enemy.physicsBody?.affectedByGravity = false
enemy.physicsBody?.categoryBitMask = enemyCategory
// enemy.physicsBody?.contactTestBitMask = shipCategory
enemy.physicsBody?.collisionBitMask = 0
// 衝突しても衝突相手からの力を受けないように設定
// 敵スプライトの縦方向のアクションを定義する:
//1. 敵発生音を再生する
// 2. (シーン縦幅 + 敵スプライト高さ)分の距離を縦方向に3〜6秒の時間(ランダム時間)で移動する
// 3. 敵スプライトをシーンから削除する
let verticalAction = SKAction.sequence([
SKAction.playSoundFileNamed("enemy_spawn.wav", waitForCompletion: false),
SKAction.moveBy(x: 0, y: -(size.height + enemy.size.height * 0.5), duration: TimeInterval(Int(3 + arc4random_uniform(3)))),
SKAction.removeFromParent()
])
// 敵スプライトの横方向のアクションを定義する:
// 以下の操作をずっと繰り返す:
// 1. 0.5〜2秒(ランダム時間)待つ
// 2. -50〜50の距離(ランダム距離)を縦方向に0.5秒で移動する
let horizontalAction = SKAction.repeatForever(
SKAction.sequence([
SKAction.wait(forDuration: 0.9, withRange: 3),
SKAction.run {
enemy.run(SKAction.moveBy(x: 50.0 - CGFloat(arc4random_uniform(100)), y: 0, duration: 0.5))
}
])
)
// 敵スプライトからビームを発射するアクションを定義する
// 以下の操作をずっと繰り返す:
// 1. 0.2~1秒(ランダム時間)待つ
// 2. ビーム発射メソッドを実行する
let beamAction = SKAction.repeatForever(
SKAction.sequence([
SKAction.wait(forDuration: 0.9, withRange: 3),
SKAction.run {
self.spawnEnemyBeam(enemy: enemy);
}
])
)
enemy.run(SKAction.group([verticalAction, horizontalAction, beamAction]))
addChild(enemy)
}
// 敵のビームを生成するメソッド
private func spawnEnemyBeam(enemy: SKSpriteNode) {
let beam = SKSpriteNode(imageNamed: "enemy_beam")
beam.anchorPoint = CGPoint(x: 0.5, y: 0)
// 敵ビームスプライトの中央下側を原点とする
beam.position = CGPoint(x: enemy.position.x, y: enemy.position.y - enemy.size.height * 0.5)
// 敵スプライトの先端にビームを配置する
beam.zPosition = enemy.zPosition - 1
// 敵スプライトの背面にビームを配置する
beam.name = "enemy_beam"
// 敵ビームの物理衝突の設定を行う
beam.physicsBody = SKPhysicsBody(rectangleOf: beam.size)
// 敵ビーム衝突用の物理ボディを用意する
beam.physicsBody?.affectedByGravity = false
// 重力の影響は受けないように設定
beam.physicsBody?.categoryBitMask = beamCategory
beam.physicsBody?.contactTestBitMask = playerCategory
beam.physicsBody?.collisionBitMask = 0
// 衝突しても衝突相手からの力を受けないように設定
// ビーム用に以下のアクションを定義する:
// 1. 敵ビーム発射音を再生する
// 2. シーンの高さ分の距離だけ縦方向に0.75秒かけて移動する
// 3. 敵ビームスプライトをシーンから削除する
let action = SKAction.sequence([
SKAction.playSoundFileNamed("enemy_beam.wav", waitForCompletion: false),
SKAction.moveBy(x: 0, y: -size.height, duration: 0.75),
SKAction.removeFromParent()
])
beam.run(action)
addChild(beam)
}
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let touchedNode = atPoint(location)
if touchedNode.name == "ship" {
shoot()
}
if touchedNode.name == "button" {
let gameOverScene = GameScene(size: self.frame.size)
self.view?.presentScene(gameOverScene)
}
}
}
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
for touch in touches {
let toucLocation = touch.location(in: self)
ship.position.x = toucLocation.x
}
}
override func update(_ currentTime: TimeInterval) {
if lastUpdateTime2 == 0 {
lastUpdateTime2 = currentTime
}
if currentTime - lastUpdateTime2 > 3 {
// 更新コマンドは3秒ごとに起動
spawnEnemy()
lastUpdateTime2 = currentTime
}
}
func didBegin(_ contact: SKPhysicsContact) {
var firstBody, 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 == playerCategory &&
secondBody.categoryBitMask == enemyCategory {
secondBody.node?.removeFromParent()
score -= 1
label.text = "\(score)"
if self.score <= 1 {
score = 50
}
}
if firstBody.categoryBitMask == beamCategory &&
secondBody.categoryBitMask == playerCategory {
secondBody.node?.removeFromParent()
label2.text = "GameOver"
}
if firstBody.categoryBitMask == playerCategory &&
secondBody.categoryBitMask == ballCategory {
contact.bodyB.node?.removeFromParent()
score -= 1
label.text = "\(score)"
if self.score <= 1 {
score = 50
}
}
if firstBody.categoryBitMask == playerCategory &&
secondBody.categoryBitMask == rectCategory {
contact.bodyB.node?.removeFromParent()
score -= 1
label.text = "\(score)"
if self.score <= 1 {
score = 50
}
}
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
}
}
import SwiftUI
import SpriteKit
extension List {
func listBackground(_ color: Color) -> some View {
UITableView.appearance().backgroundColor = UIColor(color)
return self
}
}
struct ContentView: View {
private let myurl = URL(string: "https://tate.gif.jp/img/d01.jpg")
var body: some View {
NavigationView {
List {
Image("c03")
.resizable()
.aspectRatio(contentMode: .fill)
// .frame(maxWidth: .infinity, maxHeight: 40)
.frame(maxWidth: 40, maxHeight: 40)
.clipped()
HStack {
Circle()
.frame(width: 40, height: 40)
.foregroundColor(.green)
Text("mytitle")
}
NavigationLink(destination: GameA()) {
HStack() {
// Image("c03")
AsyncImage(url: myurl, scale: 7.2)
// .resizable()
.scaledToFill()
.frame(maxWidth: 40, maxHeight: 40)
.clipped()
.cornerRadius(4)
// Spacer(minLength: 1)
.padding(.trailing, 50)
Text("画像とテキストを表示")
}
} .listRowBackground(Color.orange)
NavigationLink(destination: SKContentView()) {
Text("Game").foregroundColor(.blue)
.fontWeight(.black)
}
.listRowBackground(Color.yellow)
NavigationLink(destination: Game2()) {
(Text("G") + Text("a")
.foregroundColor(Color.red)
.fontWeight(.black) + Text("me2"))
}
NavigationLink(destination: Game3()) {
Text("Game3")
.font(.custom("Times-Roman", size: 25))
}
.listRowBackground(Color.red)
NavigationLink(destination: Game4()) {
Text("Game4")
.font(.system(size: 20, weight: .black, design: .default))
}
// .listRowBackground(Color.clear)
.listRowBackground(Color(red: 0.1, green: 0.9, blue: 0.1, opacity: 0.6))
}.listBackground(.blue)
.listStyle(InsetListStyle())
// .navigationTitle("Game a player")
}
}
}
struct Game: 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 Game2: View {
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
var scene: SKScene {
let scene = GameScene2()
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 Game3: View {
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
var scene: SKScene {
let scene = GameScene3()
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 Game4: View {
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
var scene: SKScene {
let scene = GameScene4()
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 GameA: View {
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
var scene: SKScene {
let scene = GameSceneA()
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 GameB: View {
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
var scene: SKScene {
let scene = GameSceneB()
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()
}
}
///////////////////
GameScene
import SwiftUI
import SpriteKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
backgroundColor = .yellow
let TitleLabel = SKLabelNode(fontNamed: "Verdana-bold")
TitleLabel.text = "GameScene"
TitleLabel.fontSize = 30
TitleLabel.horizontalAlignmentMode = .center
TitleLabel.fontColor = SKColor.black
TitleLabel.position = CGPoint(x:175, y:370)
self.addChild(TitleLabel)
}
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
}
}
struct SKContentView: View {
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
@Environment(\.dismiss) var dismiss
var name: String = "Hello SwiftUI!"
var scene: SKScene {
let scene = GameScene()
scene.size = CGSize(width: screenWidth, height: screenHeight)
scene.scaleMode = .fill
return scene
}
var body: some View {
ZStack {
Color.blue
.ignoresSafeArea()
VStack {
SpriteView(scene: scene)
.frame(width: screenWidth, height: screenHeight)
.ignoresSafeArea()
}
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(
action: {
dismiss()
}, label: {
Image(systemName: "arrow.backward")
Text("戻る")
}
).tint(.blue)
}
}
}
}
}
struct SKContentView_Previews: PreviewProvider {
static var previews: some View {
SKContentView()
}
///////////////////////
GameScene3
class GameScene3: SKScene {
let NextLabel = SKLabelNode(fontNamed: "Verdana-bold")
override func didMove(to view: SKView) {
backgroundColor = .red
let TitleLabel = SKLabelNode(fontNamed: "Verdana-bold")
TitleLabel.text = "GameScene3"
TitleLabel.fontSize = 30
TitleLabel.horizontalAlignmentMode = .center
TitleLabel.fontColor = SKColor.black
TitleLabel.position = CGPoint(x:175, y:370)
self.addChild(TitleLabel)
NextLabel.text = "SceneA-bへGO"
NextLabel.fontSize = 30
NextLabel.horizontalAlignmentMode = .center
NextLabel.fontColor = SKColor.black
NextLabel.position = CGPoint(x:175, y:570)
self.addChild(NextLabel)
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
let breakOutGameScene = GameScene4(size: self.size)
self.view?.presentScene(breakOutGameScene)
}
}
//////////////////////
GameScene4
import SwiftUI
import SpriteKit
class GameScene4: SKScene {
override func didMove(to view: SKView) {
backgroundColor = .green
let TitleLabel = SKLabelNode(fontNamed: "Verdana-bold")
TitleLabel.text = "GameSceneAへ"
TitleLabel.fontSize = 30
TitleLabel.horizontalAlignmentMode = .center
TitleLabel.fontColor = SKColor.black
TitleLabel.position = CGPoint(x:175, y:370)
TitleLabel.name = "tail"
self.addChild(TitleLabel)
}
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 == "tail" {
// let reveal = SKTransition.doorway(withDuration: 1)
let scene = GameSceneA(size: self.size)
let skView = self.view!
scene.scaleMode = SKSceneScaleMode.aspectFit
// skView.presentScene(scene, transition: reveal)
skView.presentScene(scene)
}
}
}
}
//////////////////////////////////////
GameSceneA
import SpriteKit
import GameplayKit
class GameSceneA: SKScene {
//各種ラベルの準備
let countLabel = SKLabelNode(fontNamed: "Verdana-bold")
let TitleLabel = SKLabelNode(fontNamed: "Verdana-bold")
let NextLabel = SKLabelNode(fontNamed: "Verdana-bold")
override func didMove(to view: SKView) {
self.backgroundColor = UIColor.cyan
TitleLabel.text = "タイトルA"
TitleLabel.fontSize = 30
TitleLabel.horizontalAlignmentMode = .center
TitleLabel.fontColor = SKColor.black
TitleLabel.position = CGPoint(x:175, y:670)
self.addChild(TitleLabel)
NextLabel.text = "GameSceneBへGO"
NextLabel.fontSize = 30
NextLabel.horizontalAlignmentMode = .center
NextLabel.fontColor = SKColor.black
NextLabel.position = CGPoint(x:175, y:470)
NextLabel.name = "label"
self.addChild(NextLabel)
// countLabel.text = "タップは\(appDelegate.count)回"
countLabel.fontSize = 40
countLabel.horizontalAlignmentMode = .center
countLabel.fontColor = SKColor.black
countLabel.position = CGPoint(x:175, y:70)
self.addChild(countLabel)
}
func touchDown(atPoint pos : CGPoint) {
}
func touchMoved(toPoint pos : CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
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 == "label" {
// let reveal = SKTransition.doorway(withDuration: 1)
let scene = GameSceneB(size: self.size)
let skView = self.view!
scene.scaleMode = SKSceneScaleMode.aspectFit
// skView.presentScene(scene, transition: reveal)
skView.presentScene(scene)
}
}
}
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
}
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
}
override func touchesCancelled(_ touches: Set, with event: UIEvent?) {
}
override func update(_ currentTime: TimeInterval) {
}
}
//////////////////////
import SpriteKit
import GameplayKit
import CoreMotion
class GameScene: SKScene, SKPhysicsContactDelegate {
let motionManager = CMMotionManager()
var accelaration: CGFloat = 0.0
// CoreMotion // do not use
let shipCategory: UInt32 = 0x1 << 0
let missileCategory:UInt32 = 0x1 << 1
let asCategory: UInt32 = 0x1 << 2
let earthCategory: UInt32 = 0x1 << 3
var earth: SKSpriteNode!
var spaceship: SKSpriteNode!
var hearts: [SKSpriteNode] = []
var scoreLabel: SKLabelNode!
var Color1 = UIColor(red: 0.01, green: 0.1, blue: 0.4, alpha: 1.0)
var audio = SKAudioNode()
var timer: Timer?
var timerForAsteroud: Timer?
var asteroudDuration: TimeInterval = 6.0 {
didSet {
if asteroudDuration < 2.0 {
timerForAsteroud?.invalidate()
}
}
}
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
override func didMove(to view: SKView) {
backgroundColor = Color1
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
self.earth = SKSpriteNode(imageNamed: "earth")
self.earth.xScale = 1.5
self.earth.yScale = 0.3
self.earth.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 400)
self.earth.zPosition = -1.0
self.earth.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: frame.width, height: 100))
self.earth.physicsBody?.categoryBitMask = earthCategory
self.earth.physicsBody?.contactTestBitMask = asCategory
self.earth.physicsBody?.collisionBitMask = 0
addChild(self.earth)
var sizeRate : CGFloat = 0.0
var node1Size = CGSize(width: 0.0, height: 0.0)
self.spaceship = SKSpriteNode(imageNamed: "ship")
sizeRate = (frame.width / 6) / self.spaceship.size.width
node1Size = CGSize(width: self.spaceship.size.width * sizeRate,
height: self.spaceship.size.height * sizeRate)
self.spaceship.scale(to: node1Size)
self.spaceship.position = CGPoint(x: self.frame.midX, y: self.frame.maxY - 510)
self.spaceship.physicsBody = SKPhysicsBody(circleOfRadius: self.spaceship.frame.width * 0.1)
self.spaceship.physicsBody?.categoryBitMask = shipCategory
self.spaceship.physicsBody?.contactTestBitMask = asCategory
self.spaceship.physicsBody?.collisionBitMask = 0
addChild(self.spaceship)
timer = Timer.scheduledTimer(withTimeInterval: 1.6, repeats: true, block: { _ in
self.addAsteroid()
})
for i in 1...5 {
let heart = SKSpriteNode(imageNamed: "heart")
heart.position = CGPoint(x: self.frame.midX / 8 + heart.frame.height * CGFloat(i)*0.6, y: self.frame.maxY * 0.92 - heart.frame.height)
addChild(heart)
heart.setScale(0.6)
hearts.append(heart)
}
scoreLabel = SKLabelNode(text: "Score: 0")
scoreLabel.fontName = "HelveticaNeue-Bold"
scoreLabel.fontSize = 50
scoreLabel.position = CGPoint(x: self.frame.midX / 90 + scoreLabel.frame.width / 2 + 40, y: self.frame.maxY * 1.15 - scoreLabel.frame.height * 5)
addChild(scoreLabel)
timerForAsteroud = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true, block: { _ in
self.asteroudDuration -= 0.5
})
}
func myAudio() {
audio = SKAudioNode(fileNamed: "Sounds/beam.wav")
audio.autoplayLooped = false
addChild(audio)
let playAction = SKAction.play()
let wait = SKAction.wait(forDuration: 0.2)
let grp = SKAction.group([playAction, wait])
let rfp = SKAction.removeFromParent()
let sequence = SKAction.sequence([grp, rfp])
audio.run(sequence)
}
func myAudio2() {
audio = SKAudioNode(fileNamed: "Sounds/explosion.wav")
audio.autoplayLooped = false
addChild(audio)
let playAction = SKAction.play()
let wait = SKAction.wait(forDuration: 0.2)
let grp = SKAction.group([playAction, wait])
let rfp = SKAction.removeFromParent()
let sequence = SKAction.sequence([grp, rfp])
audio.run(sequence)
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
// myAudio()
}
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
for touch in touches {
let toucLocation = touch.location(in: self)
spaceship.position.x = toucLocation.x
}
}
func addAsteroid() {
let names = ["as1", "as2", "as3"]
let index = Int(arc4random_uniform(UInt32(names.count)))
let name = names[index]
let asteroid = SKSpriteNode(imageNamed: name)
let random = CGFloat(arc4random_uniform(UINT32_MAX)) / CGFloat(UINT32_MAX)
let positionX = frame.width * (random - 0.1)
asteroid.position = CGPoint(x: positionX + 90, y: frame.height - 50 + asteroid.frame.height)
asteroid.scale(to: CGSize(width: 40, height: 40))
asteroid.physicsBody = SKPhysicsBody(circleOfRadius: asteroid.frame.width)
asteroid.physicsBody?.categoryBitMask = asCategory
asteroid.physicsBody?.contactTestBitMask = missileCategory + shipCategory + earthCategory
asteroid.physicsBody?.collisionBitMask = 0
addChild(asteroid)
let move = SKAction.moveTo(y: -frame.height / 2 - asteroid.frame.height, duration: asteroudDuration)
let remove = SKAction.removeFromParent()
asteroid.run(SKAction.sequence([move, remove]))
}
func testParticle(atPoint: CGPoint) {
let explosion = SKEmitterNode(fileNamed: "MyParticle.sks")!
explosion.position = atPoint
explosion.name = "explosion1"
explosion.xScale = 0.6
explosion.yScale = 0.6
explosion.zPosition = 10
let action1 = SKAction.fadeOut(withDuration: 0.2)
let action2 = SKAction.removeFromParent()
let actionAll = SKAction.sequence([action1, action2])
self.addChild(explosion)
explosion.run(actionAll)
}
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
if isPaused { return }
// myAudio()
let missile = SKSpriteNode(imageNamed: "missile")
missile.position = CGPoint(x: self.spaceship.position.x, y: self.spaceship.position.y + 50)
missile.physicsBody = SKPhysicsBody(circleOfRadius: missile.frame.height / 2)
missile.physicsBody?.categoryBitMask = missileCategory
missile.physicsBody?.contactTestBitMask = asCategory
missile.physicsBody?.collisionBitMask = 0
missile.setScale(0.4)
addChild(missile)
let moveToTop = SKAction.moveTo(y: frame.height + 10, duration: 0.3)
let remove = SKAction.removeFromParent()
missile.run(SKAction.sequence([moveToTop, remove]))
}
func didBegin(_ contact: SKPhysicsContact) {
var asteroid: SKPhysicsBody
var target: SKPhysicsBody
if contact.bodyA.categoryBitMask == asCategory {
asteroid = contact.bodyA
target = contact.bodyB
} else {
asteroid = contact.bodyB
target = contact.bodyA
}
if target.categoryBitMask == missileCategory {
// myAudio2()
asteroid.node?.removeFromParent()
testParticle(atPoint: contact.contactPoint)
score += 5
}
if target.categoryBitMask == shipCategory || target.categoryBitMask == earthCategory {
guard let heart = hearts.last else { return }
heart.removeFromParent()
hearts.removeLast()
if hearts.isEmpty {
self.run(SKAction.wait(forDuration: 1)) {
let gameOverScene = GameOverScene(size: self.frame.size)
self.view?.presentScene(gameOverScene)
}
}
if self.score >= 100 {
let gameClScene = GameClearScene(size: self.frame.size)
self.view?.presentScene(gameClScene)
}
}
}
}
// GameOverScene.swift
// GameClearScene.swift
// refer Breakout