Spritekit
My WordPress site
My WordPress site
Programmingカテゴリー記事の一覧です
import SwiftUI
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate, ObservableObject { // <<: Here 1
// @Published var updates = 0
@Published var gameScore = 0 // <<: Here 2
@Published var lenght: CGFloat = 1
var up: Bool = false
// let removeLabel = SKAction.sequence([SKAction.fadeIn(withDuration: 0.3), SKAction.wait(forDuration: 0.8), SKAction.fadeOut(withDuration: 0.3)])
let tball = SKShapeNode(circleOfRadius: 20)
var lastUpdateTime2 : TimeInterval = 0
override func didMove(to view: SKView) {
backgroundColor = .yellow
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
tball.position = CGPoint(x: 0, y: 0)
tball.fillColor = .blue
self.addChild(tball)
// tball.zPosition = 10
}
func change(){
if self.lenght > 100 {
up = false
}else if (self.lenght < 10){
up = true
}
up ? (self.lenght += 1) : (self.lenght -= 1)
}
override func update(_ currentTime: TimeInterval) {
// self.change()
if lastUpdateTime2 == 0 {
lastUpdateTime2 = currentTime
}
if currentTime - lastUpdateTime2 > 1 - 0.9 {
self.change()
lastUpdateTime2 = currentTime
}
}
/*
func ball() {
let ball = SKShapeNode(circleOfRadius: 20)
let MinValue = self.size.width / 8
let MaxValue = self.size.width - 50
let SpawnPoint = UInt32(MaxValue - MinValue)
ball.position = CGPoint(x: CGFloat(arc4random_uniform(SpawnPoint)), y: 200)
ball.fillColor = .blue
self.addChild(ball)
}
*/
func ball() {
let moveDown = SKAction.moveTo(x:130, duration: 2.5)
let moveUp = SKAction.moveTo(x: -130, duration: 2.5)
let actionSequence2 = SKAction.sequence([moveDown, moveUp])
let moveRepeat = SKAction.repeatForever(actionSequence2)
tball.run(moveRepeat, withKey: "moveX")
}
func ball2() {
let moveDown2 = SKAction.moveTo(x:130, duration: -2.5)
let moveUp2 = SKAction.moveTo(x: -130, duration: -2.5)
let actionSequence3 = SKAction.sequence([moveDown2, moveUp2])
let moveRepeat2 = SKAction.repeatForever(actionSequence3)
tball.run(moveRepeat2, withKey: "moveX2")
}
func addScore(){
if gameScore < 10 {
gameScore += 1
} else {
gameScore += 5
}
}
}
struct ContentView: View {
@State var flag = true
@State var showingSheet : Bool = false
// @StateObject var gameScene = GameScene() // <<: Here 3
/*
let scene: GameScene = {
let scene = GameScene()
scene.size = CGSize(width: 300, height: 300)
scene.scaleMode = .fill
return scene
}()
*/
@StateObject private var scene: GameScene = {
let scene = GameScene()
scene.size = CGSize(width: 300, height: 300)
scene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
scene.scaleMode = .fill
return scene
}()
var body: some View {
Spacer()
VStack {
Button(action: {
if(self.flag){
scene.ball()
self.flag = false
}
else{
scene.ball2()
self.flag = true
}
}
){
Text("ball start on off")
.font(.title3)
.foregroundColor(Color.purple)
.padding(.bottom, 20)
}
Button(
action: { showingSheet = true },
label: {
Text("ShowSheet")
})
.sheet(isPresented: $showingSheet){
SecondSheet()
}
}
ZStack {
SpriteView(scene: scene)
.frame(width: 300, height: 300)
.ignoresSafeArea()
Circle().frame(width: scene.lenght, height: scene.lenght)
.foregroundColor(.green)
.padding(.top, 150)
Button(action: {
scene.addScore()
}) {
Text("Score: \(scene.gameScore)")
.font(.title3)
.frame(width: 110, height: 30, alignment: .center)
.foregroundColor(Color.white)
.background(Color.pink)
.cornerRadius(5, antialiased: true)
.padding(.bottom, 130)
}
}
.padding(.bottom, 110)
}
}
struct SecondSheet: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack{
Text("SecondSheet")
.fontWeight(.heavy)
.font(.title)
Button("画面を閉じる") {
dismiss()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SwiftUI
struct ContentView: View {
@State var showHamburgerMenu = false
var body: some View {
let drag = DragGesture()
.onEnded {
if $0.translation.width < -100 {
withAnimation {
self.showHamburgerMenu = false
}
}
}
NavigationView {
GeometryReader { geometry in
ZStack(alignment: .leading) {
MainView(showHamburgerMenu: self.$showHamburgerMenu)
.frame(width: geometry.size.width, height: geometry.size.height)
.offset(x: self.showHamburgerMenu ? geometry.size.width/2 : 0)
.disabled(self.showHamburgerMenu ? true : false)
if self.showHamburgerMenu {
SideMenuView(isOpen: $showHamburgerMenu)
.frame(width: geometry.size.width)
// .frame(width: geometry.size.width/2)
.transition(.move(edge: .leading))
}
}
.gesture(drag)
}
.navigationTitle("← Menu")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(leading: (
Button(action: {
withAnimation {
self.showHamburgerMenu.toggle()
}
}) {
// Image(systemName: "line.horizontal.3")
Image(systemName: showHamburgerMenu ? "xmark" : "line.horizontal.3")
// .imageScale(.large)
.font(.title2)
.foregroundColor(.red)
}
))
}
}
}
struct MainView: View {
@Binding var showHamburgerMenu: Bool
@State var isShowSubViw = false
var body: some View {
ZStack{
Color.yellow
.frame(maxWidth: .infinity, maxHeight: .infinity)
.ignoresSafeArea()
ScrollView(.horizontal, showsIndicators: false) {
HStack{
GeometryReader { geometry in
ImageCarouselView(numberOfImages: 1) {
// Text("Bananas 🐻🐻")
Image(decorative: "d01")
.resizable()
.scaledToFit()
.frame(maxWidth: 80, maxHeight: 80, alignment: .center)
.clipShape(Circle())
}
}.frame(width: 383, height: 240)
GeometryReader { geometry in
ImageCarouselView(numberOfImages: 1) {
Text("Peaches 🍑🍑")
}
}.frame(width: 380, height: 240)
GeometryReader { geometry in
ImageCarouselView(numberOfImages: 1) {
Text("Apples 🍏🍏")
}
}.frame(width: 380, height: 240)
GeometryReader { geometry in
ImageCarouselView(numberOfImages: 1) {
Text("inuwan 🐶🐶")
}
}.frame(width: 382, height: 240)
GeometryReader { geometry in
ImageCarouselView(numberOfImages: 1) {
// Text("sakana 🐟🐟")
Image(decorative: "d04")
.resizable()
.scaledToFit()
.frame(maxWidth: 80, maxHeight: 80, alignment: .center)
.clipShape(Circle())
}
}.frame(width: 388, height: 240)
}.padding(.leading)
}
.foregroundColor(Color.white)
// .background(Color.yellow)
}
GeometryReader { geometory in
ZStack {
if isShowSubViw {
SubView()
} else {
Button(action: {
withAnimation() {
self.isShowSubViw.toggle()
}
}) {
Text("SubViewへ")
}
.padding(.top, 100)
VStack {
Text("MainView")
.font(.system(size: 35, weight: .black, design: .default))
.padding(.top, 50)
}
}
}
.frame(width: geometory.size.width,
height: geometory.size.height)
// .background(Color.yellow)
.animation(.easeInOut(duration: 0.42))
}
.transition(.move(edge: .leading))
}
}
struct SubView: View {
@State var isShowSubViw = false
let imageUrl = URL(string: "https://kyou.gif.jp/img/d07.jpg")
var body: some View {
ZStack{
LinearGradient(gradient: Gradient(colors: [Color.yellow, Color.green]), startPoint: .init(x: 0.3, y: 0.3), endPoint: .init(x: 0.55, y: 0.55))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.ignoresSafeArea()
VStack{
AsyncImage(url: imageUrl) { image in
image.resizable()
.aspectRatio(contentMode: .fill)
.clipShape(Circle())
} placeholder: {
ProgressView()
}
.frame(width: 80, height: 80, alignment: .center)
.padding(.bottom, 50)
.padding(.trailing, 5)
// .mask(RoundedRectangle(cornerRadius: 10))
}
GeometryReader { geometory in
ZStack {
if isShowSubViw {
MainView(showHamburgerMenu: $isShowSubViw)
} else {
Button(action: {
withAnimation() {
self.isShowSubViw.toggle()
}
}) {
Text("MainViewへ")
}
.padding(.top, 100)
VStack {
Text("SubView")
.font(.system(size: 35, weight: .black, design: .default))
.padding(.top, 50)
}
}
}
.frame(width: geometory.size.width,
height: geometory.size.height)
// .background(Color.green)
// .background(
// gradient: Gradient(colors: [Color.yellow, Color.green]),
// startPoint: .init(x: 0.3, y: 0.3), // start地点
// endPoint: .init(x: 0.55, y: 0.55) // end地点
// ))
.animation(.easeInOut(duration: 0.42))
}
.transition(.move(edge: .leading))
}
}
}
struct SideMenuView: View {
@Binding var isOpen: Bool
let width: CGFloat = 280
var body: some View {
ZStack {
GeometryReader { geometry in
EmptyView()
}
.background(Color.gray.opacity(0.3))
.opacity(self.isOpen ? 1.0 : 0.0)
.opacity(1.0)
.animation(.easeIn(duration: 0.25))
.onTapGesture {
self.isOpen = false
}
VStack(alignment: .leading) {
HStack {
Image(systemName: "person")
.foregroundColor(.white)
.imageScale(.large)
NavigationLink(destination: ProfileView()) {
Text("Profile")
.foregroundColor(.white)
.font(.headline)
}
}
.padding(.top, 80)
HStack {
Image(systemName: "envelope")
.foregroundColor(.white)
.imageScale(.large)
NavigationLink(destination: MessagesView()) {
Text("Messages")
.foregroundColor(.white)
.font(.headline)
}
}
.padding(.top, 30)
HStack {
Image(systemName: "gear")
.foregroundColor(.white)
.imageScale(.large)
NavigationLink(destination: SettingsView()) {
Text("Settings")
.foregroundColor(.white)
.font(.headline)
}
}
.padding(.top, 30)
HStack {
Image(systemName: "pencil.circle")
.foregroundColor(.white)
.imageScale(.large)
NavigationLink(destination: PencilView()) {
Text("Pencil test")
.foregroundColor(.white)
.font(.headline)
}
}
.padding(.top, 30)
Spacer()
}
// .padding()
// .frame(maxWidth: .infinity, alignment: .leading)
// .background(Color(red: 132/255, green: 132/255, blue: 132/255))
// .edgesIgnoringSafeArea(.all)
.frame(width: width)
// .background(Color(UIColor.systemGray6))
.background(Color.gray)
.offset(x: self.isOpen ? 0 : -self.width)
.animation(.easeIn(duration: 0.25))
// .padding(.top, 100)
.padding(.leading, -100)
Spacer()
}
}
}
struct PencilView: View {
var body: some View {
ZStack{
Color.purple
.frame(maxWidth: .infinity, maxHeight: .infinity)
.ignoresSafeArea()
VStack{
Text("PencilView Subview")
Text("MyPencilView")
.font(.title)
}
.navigationTitle("PencilView")
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
NavigationBackItem(title: "Menuへ戻る")
}
}
}
}
}
struct SettingsView: View {
var body: some View {
ZStack{
Color.yellow
.frame(maxWidth: .infinity, maxHeight: .infinity)
.ignoresSafeArea()
VStack{
Text("Settings Subview")
Text("MySubview")
.font(.title)
}
.navigationTitle("SettingsView")
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
NavigationBackItem(title: "Menuへ戻る")
}
}
}
}
}
struct MessagesView: View {
var body: some View {
ZStack{
Color.green
.frame(maxWidth: .infinity, maxHeight: .infinity)
.ignoresSafeArea()
VStack{
Text("Messages Subview")
}
.navigationTitle("MessagesView")
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
NavigationBackItem(title: "Menuへ戻る")
}
}
}
}
}
struct ProfileView: View {
init(){
//List全体の背景色の設定
UITableView.appearance().backgroundColor = UIColor.white
}
@State private var isNextPresented = false
var body: some View {
ZStack{
Color.orange
.frame(maxWidth: .infinity, maxHeight: .infinity)
.ignoresSafeArea()
NavigationView {
VStack{
Text("Profile Subview")
.font(.title)
List {
NavigationLink("ChildViewへ") {
ChildView()
}.listRowBackground(Color.gray.opacity(0.2))
}
}
}
// .navigationTitle("ProfileView")
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
NavigationBackItem(title: "Menuへ戻る")
}
ToolbarItem(placement: .navigationBarTrailing){
Button {
isNextPresented.toggle()
} label: {
HStack {
Text("Next")
Image(systemName: "person.fill")
}
}
.fullScreenCover(isPresented: $isNextPresented) {
NextView()
}
}
}
}
}
}
struct ChildView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
Text("ChildView")
.font(.title)
}
.navigationBarBackButtonHidden(true)
Button(action: {
dismiss()
}, label: {
Text("Profile Subviewへ")
})
}
}
struct NextView: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
VStack(spacing: 32) {
Text("Hello,NextView")
.font(.title)
Button {
dismiss()
} label: {
HStack {
Text("Nextへ")
Image(systemName: "chevron.up")
.resizable()
.frame(width: 30, height: 20)
}
}
}
}
}
struct NavigationBackItem: View {
@Environment(\.dismiss) private var dismissOn
var title : String = ""
var body: some View {
Button {
dismissOn()
} label: {
HStack {
Image(systemName: "lessthan")
.foregroundColor(.blue)
.padding(.leading, -4.0)
Text(title)
.foregroundColor(Color.blue)
.padding(.leading, -7.0)
}
}
}
}
struct ImageCarouselView: View {
private var numberOfImages: Int
private var content: Content
@State private var currentIndex: Int = 0
private let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
init(numberOfImages: Int, @ViewBuilder content: () -> Content) {
self.numberOfImages = numberOfImages
self.content = content()
}
var body: some View {
GeometryReader { geometry in
HStack(spacing: 0) {
self.content
}
.frame(width: geometry.size.width - 50, height: geometry.size.height - 50, alignment: .center)
.offset(x: CGFloat(self.currentIndex) * -geometry.size.width, y: 0)
.animation(.spring())
.onReceive(self.timer) { _ in
self.currentIndex = (self.currentIndex + 1) % 5
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SwiftUI
struct ContentView: View {
@State var selectedTag = 1
var body: some View {
TabView(selection: $selectedTag) {
HomeTabView().tag(1)
WeatherTabView().tag(2)
NewsTabView().tag(3)
NewsTabView2().tag(4)
NewsTabView3().tag(5)
}
.tabViewStyle(PageTabViewStyle())
.ignoresSafeArea()
}
}
struct HomeTabView: View {
var body: some View {
VStack {
Image(systemName: "music.note.house")
.scaleEffect(x: 3.0, y: 3.0)
.frame(width: 100, height: 100)
Text("HOME").font(.system(size: 40))
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(red: 0.5, green: 0.9, blue: 0.9))
.ignoresSafeArea()
}
}
struct WeatherTabView: View {
var body: some View {
VStack {
Image(systemName: "cloud.sun")
.scaleEffect(x: 3.0, y: 3.0)
.frame(width: 100, height: 100)
Text("Weather").font(.system(size: 40))
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(red: 1.0, green: 0.9, blue: 1.0))
.ignoresSafeArea()
}
}
struct NewsTabView: View {
var body: some View {
VStack {
Image(systemName: "newspaper")
.scaleEffect(x: 3.0, y: 3.0)
.frame(width: 100, height: 100)
Text("News").font(.system(size: 40))
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(red: 0.9, green: 0.9, blue: 0.8))
.ignoresSafeArea()
}
}
struct NewsTabView2: View {
@State var isShowSubViw = false
var body: some View {
GeometryReader { geometory in
ZStack {
VStack {
Image(systemName: "ant.circle.fill")
.scaleEffect(x: 3.0, y: 3.0)
.frame(width: 100, height: 100)
Text("NewsTabView2")
.font(.system(size: 40, weight: .black, design: .default))
.padding(.top, -20)
}
if isShowSubViw {
SubView()
} else {
Button(action: {
withAnimation() {
self.isShowSubViw.toggle()
}
}) {
Text("SubViewへ遷移")
.padding(.top, 200)
}
}
}
.frame(width: geometory.size.width,
height: geometory.size.height)
.background(Color.green)
.animation(.easeInOut(duration: 0.42))
}
.transition(.move(edge: .leading))
}
}
struct SubView: View {
@State var isShowSubViw = false
var body: some View {
GeometryReader { geometory in
ZStack {
if isShowSubViw {
NewsTabView2()
} else {
Button(action: {
withAnimation() {
self.isShowSubViw.toggle()
}
}) {
Text("NewsTabView2へ戻る")
}
.padding(.top, 100)
VStack {
Text("SubView")
.font(.system(size: 40, weight: .black, design: .default))
}
}
.frame(width: geometory.size.width,
height: geometory.size.height)
.background(
LinearGradient(
gradient: Gradient(colors: [Color.yellow, Color.red]),
startPoint: .init(x: 0.3, y: 0.3), // start地点
endPoint: .init(x: 0.55, y: 0.55) // end地点 。
))
.animation(.easeInOut(duration: 0.42))
}
.transition(.move(edge: .leading))
}
}
struct NewsTabView3: View {
@State var isShow: Bool = false
var body: some View {
VStack {
Image(systemName: "ladybug.fill")
.scaleEffect(x: 3.0, y: 3.0)
.frame(width: 100, height: 100)
Text("First View").font(.system(size: 30))
.padding(.bottom, 30)
Button(action: {
withAnimation {
self.isShow.toggle()
}
}) {
Text("Second View pageへ").font(.system(size: 20))
}
.fullScreenCover(isPresented: $isShow){
SomeView(isPresented: $isShow) // SomeViewビューを表示する
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.yellow)
.ignoresSafeArea()
}
}
struct SomeView: View {
// ContentViewビューの変数isShowとバインディングする
@Binding var isPresented: Bool
var body: some View {
NavigationView {
VStack {
Image(systemName: "ladybug").scaleEffect(2.0)
Text("Second View").font(.title2).padding()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(
LinearGradient(
gradient: Gradient(colors: [Color.yellow, Color.green]),
startPoint: .init(x: 0.3, y: 0.3), // start地点
endPoint: .init(x: 0.55, y: 0.55) // end地点
))
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button {
isPresented = false
} label: {
HStack {
Image(systemName:"lessthan")
.foregroundColor(.green)
Text("First Viewへ戻る")
.foregroundColor(Color.green)
}
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SwiftUI
extension Text {
func textModifier(color: Color) -> some View {
self
.font(.system(size: 14, design: .monospaced))
.fontWeight(.bold) // Viewに準拠していないModifier
.multilineTextAlignment(.center) // Viewに準拠していないModifier
.padding(7)
.overlay(RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 1))
.foregroundColor(color)
}
}
struct ContentView: View {
let pi = 3.141519 // 円周率z
@State private var text: String = """
A text editor view allows you to display and edit multiline,scrollable text in your app’s user interface.
複数行のスクロール可能なテキストを表示・編集できる
"""
var body: some View {
VStack {
Text("myテキスト")
.textModifier(color: .red)
Text("円周率:\(pi, specifier: "%.2f")")
.font(.system(size: 40, weight: .black, design: .default))
.foregroundColor(.green)
.padding(.top, 10)
TextEditor(text: $text)
.frame(width: 320, height: 150)
.padding(.bottom, -20)
Text("Hello, world!").kerning(5)
.font(.custom("Times-Roman", size: 35))
.padding(.top, 20)
Text("エリア 200 x 200 の中に文章を中央寄りで表示します。よろしくお願いいたします。")
.frame(width: 280, height: 100, alignment: .leading)
.multilineTextAlignment(.leading)
.lineSpacing(10)
Text("SwiftUI")
.font(.system(size: 50, weight: .black, design: .default))
Divider().padding(.bottom, 10)
Text("SwiftUIで") +
Text("一部の文字").foregroundColor(.red).fontWeight(.bold) + Text("だけを装飾する。")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SpriteKit
import GameplayKit
class GameScene: SKScene {
let label = SKLabelNode(fontNamed: "HelveticaNeue-Light")
let button = SKSpriteNode(imageNamed: "blue2.png")
let button2 = SKLabelNode(text: "Button")
var n = 0
let label2 = SKLabelNode(text: "kaisu: 0kai")
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)
let labelSize: CGFloat = 30.0
label2.fontSize = labelSize
label2.fontName = "Avenir-Black"
label2.position = CGPoint(x:self.frame.midX, y: 200)
label2.fontColor = SKColor.black
self.addChild(label2)
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
button2.fontName = "HelveticaNeue-Bold"
let labelSize2: CGFloat = 30.0
button2.fontSize = labelSize2
button2.position = CGPoint(x:self.frame.midX, y:250)
self.addChild(button2)
button2.name = "button2"
button2.color = .blue
}
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
button.alpha = 1
button.setScale(0.5)
}
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
guard let touch = touches.first else { return }
let toucLocation = touch.location(in: self)
button2.position.x = toucLocation.x
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
let tappedNodes = nodes(at: location)
for node in tappedNodes {
if node.name == "button" {
button.alpha = 0.5
button.setScale(0.6)
if label.fontSize < 50 {
label.fontSize += 2
}
else{ label.fontSize = 20
}
} else if node.name == "button2" {
button2.fontSize += 1
n += 1
label2.text = "kaisu: \(n)kai"
if button2.fontSize >= 50{
button2.fontSize = 30
}
}
}
}
}
import SpriteKit
import GameplayKit
enum CollisionTypes: UInt32 {
case ship = 1
case bullet = 2
case enemy = 4
case beam = 8
case rect = 16
case ball = 32
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var label = SKLabelNode(fontNamed: "HelveticaNeue-Light")
var score = 5
var ship = SKSpriteNode()
var bullet : SKSpriteNode!
var enemy : SKSpriteNode!
var beam : SKSpriteNode!
var touched:Bool = false
var lastUpdateTime2 : TimeInterval = 0
var myrect : SKShapeNode!
var ball : SKShapeNode!
let red = CGFloat.random(in: 0...1)
let gr = CGFloat.random(in: 0...1)
let bl = CGFloat.random(in: 0...1)
override func didMove(to view: SKView) {
backgroundColor = .blue
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)
shipstart()
rectTo()
ballTo()
}
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)
}
func rectTo(){
for _ in 0...7 {
myrect = SKShapeNode(rectOf: CGSize(width:40, height:40),cornerRadius: 5)
myrect.position = CGPoint(x: Int.random(in: 50...350), y: Int.random(in: 450...600))
myrect.fillColor = randomColor(opacity: 1.0)
myrect.lineWidth = 0.0
myrect.physicsBody = SKPhysicsBody(rectangleOf:myrect.frame.size)
myrect.physicsBody?.affectedByGravity = false
myrect.physicsBody?.isDynamic = false
myrect.name = "rect"
self.addChild(myrect)
myrect.physicsBody?.categoryBitMask = CollisionTypes.rect.rawValue
}
}
func ballTo(){
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 = 18
ball = SKShapeNode(circleOfRadius: radius)
let randIntX = CGFloat(Int.random(in : 0...300) + 50)
let randIntY = CGFloat(Int.random(in : 0...200) + 150)
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 = CollisionTypes.ball.rawValue
}
}
func shipstart(){
ship = SKSpriteNode(imageNamed: "ship")
ship.position = CGPoint(x: self.frame.midX, y: frame.height / 11 )
ship.setScale(1.2)
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 = CollisionTypes.ship.rawValue
ship.physicsBody?.collisionBitMask = 0
}
func shoot() {
bullet = SKSpriteNode(imageNamed: "beam")
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?.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 = CollisionTypes.bullet.rawValue
bullet.physicsBody?.contactTestBitMask = CollisionTypes.enemy.rawValue | CollisionTypes.rect.rawValue | CollisionTypes.ball.rawValue
// bullet.position = CGPoint(x: self.ship.position.x - 2, y: self.ship.position.y)
let move = SKAction.moveTo(y: frame.height, duration: 0.6)
let remove = SKAction.removeFromParent()
bullet.run(SKAction.sequence([move, remove]))
}
// teki
private func spawnEnemy() {
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) enemy.position.y = size.height + enemy.size.height * 0.5
enemy.zPosition = ship.zPosition + 10
enemy.name = "enemy"
enemy.setScale(0.9)
enemy.physicsBody = SKPhysicsBody(rectangleOf: enemy.size)
enemy.physicsBody?.affectedByGravity = false
enemy.physicsBody?.categoryBitMask = CollisionTypes.enemy.rawValue
enemy.physicsBody?.contactTestBitMask = shipCategory
enemy.physicsBody?.collisionBitMask = 0
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()
])
let horizontalAction = SKAction.repeatForever(
SKAction.sequence([
SKAction.wait(forDuration: 0.9, withRange: 3),
SKAction.run {
self.enemy.run(SKAction.moveBy(x: 50.0 - CGFloat(arc4random_uniform(100)), y: 0, duration: 0.5))
}
])
)
let beamAction = SKAction.repeatForever(
SKAction.sequence([
SKAction.wait(forDuration: 0.9, withRange: 3),
SKAction.run {
self.spawnEnemyBeam(enemy: self.enemy);
}
])
)
enemy.run(SKAction.group([verticalAction, horizontalAction, beamAction]))
addChild(enemy)
}
private func spawnEnemyBeam(enemy: SKSpriteNode) {
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 = CollisionTypes.beam.rawValue
beam.physicsBody?.contactTestBitMask = CollisionTypes.ship.rawValue | CollisionTypes.ball.rawValue
beam.physicsBody?.collisionBitMask = 0
let action = SKAction.sequence([
SKAction.playSoundFileNamed("enemy_beam.wav", waitForCompletion: false),
SKAction.moveBy(x: 0, y: -size.height, duration: 0.8),
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()
}
}
}
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
// for touch in touches {
// let toucLocation = touch.location(in: self)
// ship.position.x = toucLocation.x
// }
guard let touch = touches.first else { return }
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) {
guard let nodeA = contact.bodyA.node else { return }
guard let nodeB = contact.bodyB.node else { return }
if nodeA == bullet {
playerCollided(with: nodeB)
} else if nodeB == bullet {
playerCollided(with: nodeA)
}
if nodeA == beam {
beamCollided(with: nodeB)
} else if nodeB == beam {
beamCollided(with: nodeA)
}
}
func beamCollided(with node: SKNode) {
if node.name == "ship" {
node.removeFromParent()
beam.removeFromParent()
let gameOverScene = GameOverScene(size: self.frame.size)
self.view?.presentScene(gameOverScene)
} else if node.name == "ball" {
node.removeFromParent()
beam.removeFromParent()
}
}
func playerCollided(with node: SKNode) {
if node.name == "enemy" {
node.removeFromParent()
bullet.removeFromParent()
score += 2
label.text = "\(score)"
if self.score >= 20 {
let gameOverScene = GameClearScene(size: self.frame.size)
self.view?.presentScene(gameOverScene)
}
} else if node.name == "rect" {
node.removeFromParent()
bullet.removeFromParent()
}else if node.name == "ball" {
node.removeFromParent()
bullet.removeFromParent()
}
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
}