spritekitカテゴリー記事の一覧です
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
}
}
level1
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
ayaaa
aaaaasaaaaaa
yaaaaaaaaaaa
import SpriteKit
import GameplayKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
backgroundColor = UIColor.white
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
let myLabel = SKLabelNode(fontNamed: "Arial")
myLabel.text = "Start"
myLabel.fontSize = self.frame.width / 8
myLabel.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
myLabel.fontColor = SKColor.blue
self.addChild(myLabel)
let fadeInAction = SKAction.fadeAlpha(to: 1.0, duration: 3.0)
let fadeOutAction = SKAction.fadeAlpha(to: 0.0, duration: 3.0)
let changeLabelTextAction = SKAction.run({
myLabel.text = "New Text"
})
let actionSequence = SKAction.sequence([fadeOutAction, changeLabelTextAction, fadeInAction])
myLabel.run(actionSequence)
// run(SKAction.repeat(SKAction.sequence([SKAction.run(createBall), SKAction.wait(forDuration: 0.6)]), count: 20))
let timerWait = SKAction.wait(forDuration: 0.6)
let shotCheck = SKAction.run {self.createBall()}
let shotSequence = SKAction.sequence([shotCheck, timerWait])
let loopShotCheck = SKAction.repeat(shotSequence, count: 20)
self.run(loopShotCheck)
}
func createBall() {
let ball = SKShapeNode(circleOfRadius: 50)//circleOfRadiusで円の半径
ball.position = CGPoint(x:self.frame.midX, y:self.frame.midY+250)
ball.fillColor = UIColor.red
ball.lineWidth = 4.0
ball.strokeColor = UIColor.lightGray
// let ball = SKSpriteNode(imageNamed: "ball")
// ball.position = CGPoint(x: CGFloat(Int.random(in: 0...400) + 200),
// y: size.height - ball.frame.height)
ball.position = CGPoint(x: CGFloat(Int(arc4random()) % Int(size.width)),
y: size.height - ball.frame.height)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width/2)
addChild(ball)
}
}
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
}
}
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()
// score += 1
} else if node.name == "bottom" {
player.removeFromParent()
testAudio()
}
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
}
}