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
Sound
import SpriteKit
import GameplayKit
import AVFoundation
class GameScene: SKScene {
var toggle:Bool = true
let volSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
let defaultMax = Float(0.123456789)
var player: AVPlayer!
var videoNode: SKVideoNode!
@objc func volSliderChangedValue(sender: UISlider) {
player.volume = sender.value
}
override func didMove(to view: SKView) {
removeAllChildren() // Delete this in your actual project.
let label = SKLabelNode(fontNamed: "HelveticaNeue-Light")
label.text = "Sound On Off"
let labelSize: CGFloat = 30.0
label.fontSize = labelSize
label.position = CGPoint(x:self.frame.midX, y:self.frame.height/2 + 70)
label.fontColor = SKColor.yellow
self.addChild(label)
label.name = "button"
let volLabel = SKLabelNode(text: "Volume")
volLabel.setScale(0.6)
volLabel.verticalAlignmentMode = .center
volLabel.position = CGPoint(x: frame.minX + 120, y: frame.minY + 360)
let url = Bundle.main.url(forResource: "s1", withExtension: "wav")!
player = AVPlayer(url: url)
videoNode = SKVideoNode(avPlayer: player!)
volSlider.addTarget(self, action: #selector(volSliderChangedValue), for: UIControl.Event.valueChanged)
volSlider.value = 1
let volOrigin = convertPoint(toView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
volSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
view.addSubview(volSlider)
addChild(volLabel)
addChild(videoNode)
videoNode.alpha = 0
}
func toggleTest() {
if(toggle){
videoNode.play()
toggle = false;
}else{
videoNode.pause()
toggle = true;
}
}
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" {
toggleTest()
}
}
}
}
Camera
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
let playerCategory: UInt32 = 0x1 << 0
let backgroundCategory: UInt32 = 0x1 << 1
let leftCategory: UInt32 = 0x1 << 2
var player = SKSpriteNode()
let cam = SKCameraNode()
private var background = SKSpriteNode()
override func didMove(to view: SKView) {
self.physicsWorld.gravity = CGVector( dx: 0.0, dy: 0.0 )
self.physicsWorld.contactDelegate = self
self.backgroundColor = .white
self.camera = cam
self.addChild(cam)
cam.physicsBody?.isDynamic = false
cam.physicsBody?.velocity = CGVector(dx: 60, dy: 0)
background = SKSpriteNode(imageNamed: "bg3")
background.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
background.size = CGSize(width: 4500, height: frame.size.height)
background.name = "back"
background.zPosition = -10
self.addChild(background)
background.physicsBody?.restitution = 0.9
background.physicsBody?.friction = 0
background.physicsBody?.linearDamping = 0
background.physicsBody?.isDynamic = false
createPlayer()
let leftRect = CGRect(x: 0, y: 0, width: 1, height: self.frame.size.height)
let left = SKNode()
left.physicsBody = SKPhysicsBody(edgeLoopFrom: leftRect)
self.addChild(left)
left.name = "left"
let rightRect = CGRect(x: 2040, y: 0, width: 1, height: background.frame.size.height)
background.physicsBody = SKPhysicsBody(edgeLoopFrom: rightRect)
player.physicsBody?.categoryBitMask = playerCategory
background.physicsBody?.categoryBitMask = backgroundCategory
left.physicsBody?.categoryBitMask = leftCategory
player.physicsBody?.contactTestBitMask = backgroundCategory | leftCategory
let rect = SKSpriteNode(imageNamed: "blue.png")
rect.position = CGPoint(x: 400, y: 210)
rect.size = CGSize(width: frame.size.width/2, height: frame.size.width/2)
self.addChild(rect)
let rectCopy1 = rect.copy() as! SKSpriteNode;
rectCopy1.position = CGPoint(x: 800, y: 207)
rectCopy1.color = .yellow
rectCopy1.colorBlendFactor = 1.0
self.addChild(rectCopy1)
let rectCopy2 = rect.copy() as! SKSpriteNode;
rectCopy2.position = CGPoint(x: 1200, y: 207)
rectCopy2.alpha = 0.5
self.addChild(rectCopy2)
let rectCopy3 = rect.copy() as! SKSpriteNode;
rectCopy3.position = CGPoint(x: 1600, y: 207)
rectCopy3.color = .purple
rectCopy3.colorBlendFactor = 0.6
self.addChild(rectCopy3)
let rectCopy4 = rect.copy() as! SKSpriteNode;
rectCopy4.position = CGPoint(x: 2000, y: 207)
rectCopy4.color = .yellow
rectCopy4.colorBlendFactor = 0.3
self.addChild(rectCopy4)
}
func createPlayer() {
let playerTexture = SKTexture(imageNamed: "kaeru1")
player = SKSpriteNode(texture: playerTexture)
player.zPosition = 10
player.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
addChild(player)
let f0 = SKTexture(imageNamed: "kaeru1")
let f1 = SKTexture(imageNamed: "kaeru2")
let f2 = SKTexture(imageNamed: "kaeru3")
let f3 = SKTexture(imageNamed: "kaeru4")
let f4 = SKTexture(imageNamed: "kaeru5")
let f5 = SKTexture(imageNamed: "kaeru6")
let f6 = SKTexture(imageNamed: "kaeru7")
let f7 = SKTexture(imageNamed: "kaeru8")
let animation = SKAction.animate(with: [playerTexture, f0, f1, f2, f3, f4, f5, f6, f7], timePerFrame: 0.1)
let runForever = SKAction.repeatForever(animation)
player.run(runForever)
player.xScale = -1.0
player.physicsBody = SKPhysicsBody(circleOfRadius: player.frame.width/1.55)
player.physicsBody?.friction = 0
player.physicsBody?.linearDamping = 0
player.physicsBody?.angularDamping = 0
player.physicsBody?.isDynamic = true
player.physicsBody?.allowsRotation = false
player.physicsBody?.restitution = 0.6
player.physicsBody?.velocity = CGVector(dx: 60, dy: 0)
}
override func update(_ currentTime: TimeInterval) {
super.update(currentTime)
}
//衝突判定処理
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 == playerCategory && secondBody.categoryBitMask == backgroundCategory{
firstBody.node?.xScale = 1.0
player.physicsBody?.velocity.dx = -60
}
if firstBody.categoryBitMask == playerCategory && secondBody.categoryBitMask == leftCategory{
firstBody.node?.xScale = -1.0
player.physicsBody?.velocity.dx = 60
}
}
override func didSimulatePhysics() {
self.camera?.position = CGPoint(x: self.player.position.x + 50, y:self.player.position.y)
// self.camera?.position = player.position
}
}
SpriteSheet
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var bird = SKSpriteNode()
var skyColor:SKColor!
let birdCategory: UInt32 = 0x1 << 0
let rightCategory: UInt32 = 0x1 << 1
let leftCategory: UInt32 = 0x1 << 2
override func didMove(to view: SKView) {
self.physicsWorld.gravity = CGVector( dx: 0.0, dy: -2 )
self.physicsWorld.contactDelegate = self
createGround()
skyColor = SKColor(red: 81.0/255.0, green: 192.0/255.0, blue: 201.0/255.0, alpha: 1.0)
self.backgroundColor = skyColor
let framesOpening: [SKTexture] = {
let totalFrames = 10
let rows = 1
let columns = 4
let sheet = SpriteSheet(texture: SKTexture(imageNamed: "de3.png"), rows: rows, columns: columns, spacing: 0, margin: 0)
var frames = [SKTexture]()
var count = 0
for row in (0.., with event: UIEvent?) {
if bird.position.x >= self.frame.size.width{
bird.physicsBody?.velocity.dx = -60
}
if bird.position.x <= 0{
bird.physicsBody?.velocity.dx = 60
}
bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 50))
}
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 == birdCategory && secondBody.categoryBitMask == rightCategory{
firstBody.node?.xScale = -1.0
createGround2()
bird.physicsBody?.velocity.dx = -60
}
if firstBody.categoryBitMask == birdCategory && secondBody.categoryBitMask == leftCategory{
firstBody.node?.xScale = 1.0
createGround()
bird.physicsBody?.velocity.dx = 60
}
}
func createGround() {
let groundTexture = SKTexture(imageNamed: "ground")
for i in 0 ... 1 {
let ground = SKSpriteNode(texture: groundTexture)
ground.zPosition = -10
ground.position = CGPoint(x: (groundTexture.size().width / 2.0 + (groundTexture.size().width * CGFloat(i))), y: groundTexture.size().height / 4)
addChild(ground)
let moveLeft = SKAction.moveBy(x: -groundTexture.size().width, y: 0, duration: 10)
let moveReset = SKAction.moveBy(x: groundTexture.size().width, y: 0, duration: 0)
let moveLoop = SKAction.sequence([moveLeft, moveReset])
let moveForever = SKAction.repeatForever(moveLoop)
ground.run(moveForever)
//当たり判定の大きさ
ground.physicsBody = SKPhysicsBody(rectangleOf: ground.frame.size)
ground.physicsBody?.restitution = 0.4
ground.physicsBody?.friction = 0
ground.physicsBody?.linearDamping = 0
ground.physicsBody?.isDynamic = false
}
}
func createGround2() {
let groundTexture = SKTexture(imageNamed: "ground")
for i in 0 ... 1 {
let ground = SKSpriteNode(texture: groundTexture)
ground.zPosition = -10
ground.position = CGPoint(x: (groundTexture.size().width / 2.0 + (groundTexture.size().width * CGFloat(i))), y: groundTexture.size().height / 4)
addChild(ground)
let moveright = SKAction.moveBy(x: -groundTexture.size().width, y: 0, duration: 0)
let moveReset = SKAction.moveBy(x: groundTexture.size().width, y: 0, duration: 10)
let moveLoop = SKAction.sequence([moveright, moveReset])
let moveForever = SKAction.repeatForever(moveLoop)
ground.run(moveForever)
ground.physicsBody = SKPhysicsBody(rectangleOf: ground.frame.size)
ground.physicsBody?.restitution = 0.4
ground.physicsBody?.friction = 0
ground.physicsBody?.linearDamping = 0
ground.physicsBody?.isDynamic = false
}
}
}
class SpriteSheet {
let texture: SKTexture
let rows: Int
let columns: Int
var margin: CGFloat=0
var spacing: CGFloat=0
var frameSize: CGSize {
return CGSize(width: (self.texture.size().width-(self.margin*2+self.spacing*CGFloat(self.columns-1)))/CGFloat(self.columns),
height: (self.texture.size().height-(self.margin*2+self.spacing*CGFloat(self.rows-1)))/CGFloat(self.rows))
}
init(texture: SKTexture, rows: Int, columns: Int, spacing: CGFloat, margin: CGFloat) {
self.texture=texture
self.rows=rows
self.columns=columns
self.spacing=spacing
self.margin=margin
}
convenience init(texture: SKTexture, rows: Int, columns: Int) {
self.init(texture: texture, rows: rows, columns: columns, spacing: 0, margin: 0)
}
func textureForColumn(column: Int, row: Int)->SKTexture? {
if !(0...self.rows ~= row && 0...self.columns ~= column) {
return nil
}
var textureRect = CGRect(x: self.margin + CGFloat(column) * (self.frameSize.width+self.spacing)-self.spacing, y: self.margin + CGFloat(self.rows - row - 1) * (self.frameSize.height+self.spacing)-self.spacing,
height: self.frameSize.height)
textureRect = CGRect(x: textureRect.origin.x/self.texture.size().width, y: textureRect.origin.y/self.texture.size().height,
width: textureRect.size.width/self.texture.size().width, height: textureRect.size.height/self.texture.size().height)
return SKTexture(rect: textureRect, in: self.texture)
}
}
SKPhysics42
import SpriteKit
import GameplayKit
extension SKPhysicsBody {
func ideal() -> SKPhysicsBody {
self.friction = 0
self.linearDamping = 0
self.angularDamping = 0
self.restitution = 0.98
self.isDynamic = true
self.allowsRotation = false
self.affectedByGravity = true
return self
}
}
enum CollisionTypes: UInt32 {
case player = 1
case squareA = 2
case squareB = 4
case bottom = 8
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var n = 0
let label = SKLabelNode(text: "kaisu: 0kai")
var audio = SKAudioNode()
var player = SKShapeNode()
var squareA = SKShapeNode()
override func didMove(to view: SKView) {
backgroundColor = .blue
self.physicsWorld.contactDelegate = self
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
physicsWorld.gravity = CGVector(dx: 0, dy: -1.5)
let labelSize: CGFloat = 30.0
label.fontSize = labelSize
label.position = CGPoint(x:self.frame.midX, y:self.frame.height/1.12)
label.fontColor = SKColor.white
self.addChild(label)
player = SKShapeNode(circleOfRadius: 30)
player.position = CGPoint(x:self.frame.midX, y:self.frame.midY + 140)
player.fillColor = UIColor.red
player.lineWidth = 4.0
player.strokeColor = UIColor.lightGray
self.addChild(player)
player.name = "player"
player.physicsBody = SKPhysicsBody(circleOfRadius: player.frame.width/2).ideal()
squareA = SKShapeNode(rectOf: CGSize(width:50, height:50),cornerRadius: 3)
squareA.position = CGPoint(x:self.frame.midX, y:self.frame.midY + 10)
squareA.fillColor = UIColor.yellow
squareA.lineWidth = 2.0
squareA.strokeColor = UIColor.lightGray
self.addChild(squareA)
squareA.name = "squareA"
squareA.physicsBody = SKPhysicsBody(rectangleOf: squareA.frame.size).ideal()
squareA.physicsBody?.affectedByGravity = false
let squareB = SKShapeNode(rectOf: CGSize(width:100, height:100),cornerRadius: 5)
squareB.position = CGPoint(x:self.frame.midX, y:self.frame.midY - 200)
squareB.fillColor = .green
squareB.lineWidth = 0.0
self.addChild(squareB)
squareB.name = "squareB"
squareB.physicsBody = SKPhysicsBody(rectangleOf: squareB.frame.size).ideal()
let bottomRect = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: 1)
let bottom = SKNode()
bottom.physicsBody = SKPhysicsBody(edgeLoopFrom: bottomRect)
self.addChild(bottom)
bottom.name = "bottom"
player.physicsBody?.categoryBitMask = CollisionTypes.player.rawValue
squareA.physicsBody?.categoryBitMask = CollisionTypes.squareA.rawValue
squareB.physicsBody?.categoryBitMask = CollisionTypes.squareB.rawValue
//bottomカテゴリ
bottom.physicsBody?.categoryBitMask = CollisionTypes.bottom.rawValue
player.physicsBody?.contactTestBitMask = CollisionTypes.squareA.rawValue | CollisionTypes.squareB.rawValue | CollisionTypes.bottom.rawValue
}
func testAudio() {
audio = SKAudioNode(fileNamed: "Sounds/sound.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 testParticle() {
let explosion = SKEmitterNode(fileNamed: "MyParticle.sks")!
explosion.position = CGPoint(x: squareA.position.x, y: squareA.position.y + squareA.frame.size.height * 0.5)
// explosion.position = squareA.position
// beam.position = CGPoint(x: player.position.x, y: player.position.y + player.size.height * 0.5)
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)
}
func didBegin(_ contact: SKPhysicsContact) {
n += 1
label.text = "kaisu: \(n)kai"
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 == "squareA" {
testAudio()
testParticle()
node.removeFromParent()
} else if node.name == "squareB" {
node.removeFromParent()
} else if node.name == "bottom" {
player.removeFromParent()
testAudio()
}
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
}
}
physics4
import SpriteKit
import GameplayKit
extension SKPhysicsBody {
func ideal() -> SKPhysicsBody {
//摩擦係数の値で 1 に近いほど摩擦が多くなります0.0から1.0の間
self.friction = 0
self.linearDamping = 0 //粘性//体にかかる流体または空気の摩擦力
self.angularDamping = 0 //体の回転速度を遅くする特性 0.0から1.0の間の値
self.restitution = 0.98 //反発率
self.isDynamic = true //動かせる性質
self.allowsRotation = false //角力とインパルスの影響デフォルト値はtrue
// 重力を無視する 重力の影響を受けない
//circleA.physicsBody?.affectedByGravity = false
self.affectedByGravity = true
return self
}
}
class GameScene: SKScene, SKPhysicsContactDelegate {
let circleACategory: UInt32 = 0x1 << 0
let squareACategory: UInt32 = 0x1 << 1
let squareBCategory: UInt32 = 0x1 << 2
let bottomCategory:UInt32 = 0x1 << 3
var n = 0
let label = SKLabelNode(text: "kaisu: 0kai")
override func didMove(to view: SKView) {
backgroundColor = .blue
self.physicsWorld.contactDelegate = self
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
physicsWorld.gravity = CGVector(dx: 0, dy: -1.5)
let labelSize: CGFloat = 30.0
label.fontSize = labelSize
label.position = CGPoint(x:self.frame.midX, y:self.frame.height/1.12)
label.fontColor = SKColor.white
self.addChild(label)
let circleA = SKShapeNode(circleOfRadius: 40)//circleOfRadiusで円の半径
circleA.position = CGPoint(x:self.frame.midX, y:self.frame.midY + 140)
circleA.fillColor = UIColor.red
circleA.lineWidth = 4.0
circleA.strokeColor = UIColor.lightGray
self.addChild(circleA)
circleA.physicsBody = SKPhysicsBody(circleOfRadius: circleA.frame.width/2).ideal()
let squareA = SKShapeNode(rectOf: CGSize(width:50, height:50),cornerRadius: 3)
squareA.position = CGPoint(x:self.frame.midX, y:self.frame.midY + 10)
squareA.fillColor = UIColor.yellow
squareA.lineWidth = 2.0
squareA.strokeColor = UIColor.lightGray
self.addChild(squareA)
squareA.physicsBody = SKPhysicsBody(rectangleOf: squareA.frame.size).ideal()
squareA.physicsBody?.affectedByGravity = false
let squareB = SKShapeNode(rectOf: CGSize(width:100, height:100),cornerRadius: 5)
squareB.position = CGPoint(x:self.frame.midX, y:self.frame.midY - 200)
squareB.fillColor = .green
squareB.lineWidth = 0.0
self.addChild(squareB)
squareB.physicsBody = SKPhysicsBody(rectangleOf: squareB.frame.size).ideal()
let bottomRect = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: 1)
let bottom = SKNode()
bottom.physicsBody = SKPhysicsBody(edgeLoopFrom: bottomRect)
self.addChild(bottom)
//Aカテゴリ
circleA.physicsBody?.categoryBitMask = circleACategory
//Bカテゴリ
squareA.physicsBody?.categoryBitMask = squareACategory
squareB.physicsBody?.categoryBitMask = squareBCategory
//bottomカテゴリ
bottom.physicsBody?.categoryBitMask = bottomCategory
circleA.physicsBody?.contactTestBitMask = squareACategory | squareBCategory | bottomCategory
}
//衝突判定処理
func didBegin(_ contact: SKPhysicsContact) {
n += 1
label.text = "kaisu: \(n)kai"
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 == circleACategory && secondBody.categoryBitMask == squareACategory{
secondBody.node?.removeFromParent()
}
if firstBody.categoryBitMask == circleACategory && secondBody.categoryBitMask == squareBCategory{
secondBody.node?.removeFromParent()
}
if firstBody.categoryBitMask == circleACategory && secondBody.categoryBitMask == bottomCategory{
firstBody.node?.removeFromParent()
}
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
}
}