本系列文章是對<3D Apple Games by Tutorials>一書的學習記錄和體會node
此書對應的代碼地址git
SceneKit系列文章目錄github
更多iOS相關知識查看github上WeekWeekUpProjectswift
效果以下: app
項目中用到的模型是用MagicaVoxel建立的,能夠到ephtracy.github.io上去免費下載.使用教程參見本系列其餘文章.編輯器
建立項目,選擇iOS > Application > Single View Application模板. ide
更改設置,只保留豎直方向:oop
添加資源文件: 拖拽resources/GameUtils/文件夾到項目中,選擇Group: post
拖拽resources/MrPig.scnassets文件夾到項目中,選擇Create folder references:學習
完成後的效果:
添加應用圖標和啓動屏幕 在resources文件夾下找到LaunchScreen和AppIcon文件夾,拖拽到對應地方去:
給啓動屏幕添加圖片約束:
打開ViewController.swift,按下面做些修改:
// 1
import UIKit
import SceneKit
import SpriteKit
// 2
class ViewController: UIViewController {
// 3
let game = GameHelper.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
// 4
setupScenes()
setupNodes()
setupActions()
setupTraffic()
setupGestures()
setupSounds()
// 5
game.state = .tapToPlay
}
func setupScenes() {
}
func setupNodes() {
}
func setupActions() {
}
func setupTraffic() {
}
func setupGestures() {
}
func setupSounds() {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var prefersStatusBarHidden : Bool { return true }
override var shouldAutorotate : Bool { return false }
}
複製代碼
內容簡單不作過多說明,導入SpriteKit是爲了使用轉場功能.
繼續建立SceneKit View: 在ViewController的最上方添加:
var scnView: SCNView!
複製代碼
在setupScenes()中添加:
scnView = SCNView(frame: self.view.frame)
self.view.addSubview(scnView)
複製代碼
拖拽一個SceneKit Scene File到項目根目錄中,將其命名爲GameScene.scn,放在MrPig.scnassets文件夾下:
選中MrPig.scnassets/GameScene.scn的同時,拖拽一個Floor Node到場景中,並選擇Node Inspector節點檢查器,將其命名爲Grass,位置和旋轉角度設爲0:
再設置屬性檢查器,將反射Floor Reflectivity設爲0,由於草地並不須要反光:
移動到材質檢查器,設置Material Diffuse貼圖,縮放設爲12.5:
建立啓動閃屏
再拖拽一個SceneKit Scene File到項目根目錄中,將其命名爲SplashScene.scn,放在MrPig.scnassets文件夾下:
選中MrPig.scnassets/SplashScene.scn的同時,從右下角的材質庫中拖拽一個MrPig引用節點到場景中,打開其節點檢查器,將位置和旋轉設置爲零:
接着打開場景檢查器,添加漸變背景Gradient_Diffuse.png到Scene Background屬性:
爲了讓背景更好看,設置出太陽般的放射光暈效果,須要拖拽一個Plane節點到場景中,命名爲Rays,設置位置 (x:0, y:0.25, z:-1),可見度Visibility Opacity爲0.25:
打開屬性檢查器,設置Size爲 (x:5, y:5),並設置圓角半徑Corner Radius爲2.5:
打開材質檢查器Materials Inspector,將Lighting model設置爲Constant,以免光照對射線產生影響.
滾動到Settings區域並將Blend Mode混合模式設置爲Subtract減弱:
設置攝像機和燈光
點擊場景樹下方的+
號,添加一個空節點.命名爲Camera,並將原始的攝像機節點移動過來做爲子節點.選中Camera節點,打開節點檢查器,設置位置爲(x:0, y:0.3, z:0)旋轉歐拉角爲(x:-10, y:0, z:0).
選中內層的camera節點,設置位置爲(x:0, y:0, z:3)歐拉角爲(x:0, y:0, z:0).
再添加一個空節點到根目錄中,命名爲Lights,拖拽一個Ambient和一個Omni燈光到場景中:
修改omni燈光的位置,進入節點檢查器,位置改成(x:5, y:5, z:5).
添加logo和點擊開始節點
加載並展現閃屏界面
在ViewController中添加屬性:
var gameScene: SCNScene!
var splashScene: SCNScene!
複製代碼
在setupScenes() 中添加下列代碼:
// 1
gameScene = SCNScene(named: "/MrPig.scnassets/GameScene.scn")
splashScene = SCNScene(named: "/MrPig.scnassets/SplashScene.scn")
// 2
scnView.scene = splashScene
複製代碼
運行一下,效果以下:
不一樣效果的轉場動畫前面已經介紹過了. 在ViewController類中添加下面的代碼:
func startGame() {
// 1
splashScene.isPaused = true
// 2
let transition = SKTransition.doorsOpenVertical(withDuration: 1.0)
// 3
scnView.present(gameScene, with: transition, incomingPointOfView: nil, completionHandler: {
// 4
self.game.state = .playing
self.setupSounds()
self.gameScene.isPaused = false
})
}
複製代碼
繼續添加中止遊戲和開啓閃屏的方法:
func stopGame() {
game.state = .gameOver
game.reset()
}
複製代碼
func startSplash() {
// 1
gameScene.isPaused = true
// 2
let transition = SKTransition.doorsOpenVertical(withDuration: 1.0)
scnView.present(splashScene, with: transition, incomingPointOfView:
nil, completionHandler: {
self.game.state = .tapToPlay
self.setupSounds()
self.splashScene.isPaused = false
})
}
複製代碼
最後須要添加的方法是點擊開始:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
if game.state == .tapToPlay {
startGame()
}
}
複製代碼
運行後,點擊屏幕開始遊戲了.
選中MrPig.scnassets/ GameScene.scn,拖拽一個MrPig引用節點到場景中,位置和旋轉設置爲0:
在setupNodes()
中添加代碼:
pigNode = gameScene.rootNode.childNode(withName: "MrPig", recursively:true)!
複製代碼
回到MrPig.scnassets/GameScene.scn中,設置攝像機. 在場景樹中點擊+
號添加一個空節點,在節點檢查器中,將其命名爲FollowCamera,位置爲0,旋轉 (x:-45, y:20, z:0).
將已經存在的camera節點拖放到FollowCamera節點下.位置 (x:0, y:0, z:14),旋轉0.
選中ViewController.swift,添加一些屬性來控制攝像機:
var cameraNode: SCNNode!
var cameraFollowNode: SCNNode!
複製代碼
在setupNodes()
中添加下面的代碼:
// 1
cameraNode = gameScene.rootNode.childNode(withName: "camera", recursively: true)!
cameraNode.addChildNode(game.hudNode)
// 2
cameraFollowNode = gameScene.rootNode.childNode(withName: "FollowCamera", recursively: true)!
複製代碼
代碼含義:
在場景樹中點擊+
號添加一個空節點,在節點檢查器中,將其命名爲FollowLight,位置爲0,旋轉爲0.拖拽一個Ambient light和一個Directional light到空節點中.
選中ambient燈光,位置和旋轉設置爲0:
選擇屬性檢查器,設置顏色爲Aluminum:
而後選中directional燈光,進入節點檢查器,設置位置和旋轉以下:
進入屬性檢查器,配置燈光和陰影屬性:
配置完成後預覽一下:
在ViewController中添加屬性:
var lightFollowNode: SCNNode!
複製代碼
在setupNodes() 中添加下面代碼:
lightFollowNode = gameScene.rootNode.childNode(withName: "FollowLight",recursively: true)!
複製代碼
在場景樹中點擊+
號添加一個空節點,在節點檢查器中,將其命名爲Highway,拖拽兩個Road引用做爲子節點.選中第一個,設置位置 (x:0, y:0, z:-4.5),旋轉爲0:
選中第二個,位置爲 (x:0, y:0, z:-11.5),旋轉爲0:
點擊+
號添加一個空節點,在節點檢查器中,將其命名爲Traffic,拖拽一個Bus引用節點到其中,位置 (x:0, y:0, z:-4),旋轉 (x:0, y:-90, z:0):
拖拽一個Mini引用節點到其中,位置 (x:3, y:0, z:-5),旋轉 (x:0, y:-90, z:0):
拖拽一個SUV引用節點到其中,位置 (x:-3, y:0, z:-5),旋轉 (x:0, y:-90, z:0):
選中ViewController.swift,添加屬性:
var trafficNode: SCNNode!
複製代碼
在 *setupNodes()*中添加代碼:
trafficNode = gameScene.rootNode.childNode(withName: "Traffic", recursively: true)!
複製代碼
接着,須要複製一下達到下面的效果:
完成後,運行一下:
拖拽一個空的SceneKit Scene File,命名爲TreeLine並放置在MrPig.scnassets目錄下:
在TreeLine.scn中,建立一個空節點,命名爲TreeLine,它將做爲父容器節點:
按下面的圖來擺放各類樹木:
例如左上角第一個,放置一個SmallTree在位置 (x:-5, y:0, z:-1) 處.使用Option和Command鍵能夠提升複製粘貼速度.
拖拽一個空的SceneKit Scene File,命名爲TreePatch並放置在MrPig.scnassets目錄下:
在TreePatch.scn中,建立一個空節點,命名爲TreePatch,它將做爲父容器節點:
按下面的圖來擺放各類樹木:
完成後:
回到MrPig.scnassets/GameScene.scn中,添加一個空節點,命名爲Trees,做爲樹林的容器節點:
按下圖來擺放樹林TreeLine:
前面部分,靠近Mr.Pig處樹林座標爲:
公路中間處的座標爲:
後面部分的座標爲:
按下圖來擺放樹林TreePatch:
放置座標以下:
先建立一個空節點,命名爲Coins,做爲金幣的容器節點:
而後拖拽Coin引用節點到場景中,座標以下:
完成後,效果如圖:
背景射線動起來 打開MrPig.scnassets/SplashScene.scn,選中Rays.拖拽一個Rotate Action,在屬性檢查器中設置時長30,z軸360;
右鍵點擊,建立循環,點擊∞
金幣動畫
選中MrPig.scnassets/Coin.scn,按順序拖拽兩個Move Action,再並排放置一個Rotate Action
選中第一個Move Action,設置Start Time爲0,Duration爲0.5.設置Timing Function爲Ease In, Ease Out, 設置Offset爲 (x:0, y:0.5, z:0).
選中第二個Move Action,設置Start Time爲0.5,Duration爲0.5.設置Timing Function爲Ease In, Ease Out, 設置Offset爲 (x:0, y:-0.5, z:0).
選中Move Action,設置Start Time爲0,Duration爲1.設置Timing Function爲Linear, 設置Euler Angle爲 (x:0, y:360, z:0).
按Shift選中所有,而後右鍵單擊,建立循環
讓閃屏頁面的小豬動起來 進入MrPig.scnassets/SplashScreen.scn,選中MrPig,建立一系列旋轉動做:
運行一下,查看動做:
交通動做 打開ViewController.swift,添加屬性:
var driveLeftAction: SCNAction!
var driveRightAction: SCNAction!
複製代碼
在setupActions()
中添加下面代碼:
driveLeftAction = SCNAction.repeatForever(SCNAction.move(by:
SCNVector3Make(-2.0, 0, 0), duration: 1.0))
driveRightAction = SCNAction.repeatForever(SCNAction.move(by:
SCNVector3Make(2.0, 0, 0), duration: 1.0))
複製代碼
在setupTraffic()
中添加下面代碼:
// 1
for node in trafficNode.childNodes {
// 2 Buses are slow, the rest are speed demons
if node.name?.contains("Bus") == true {
driveLeftAction.speed = 1.0
driveRightAction.speed = 1.0
} else {
driveLeftAction.speed = 2.0
driveRightAction.speed = 2.0
}
// 3 Let vehicle drive towards its facing direction
if node.eulerAngles.y > 0 {
node.runAction(driveLeftAction)
} else {
node.runAction(driveRightAction)
}
}
複製代碼
運行一下,車輛動起來了,可是開過去後就沒有了,這個問題咱們稍後再處理:
添加小豬的動做
添加屬性:
var jumpLeftAction: SCNAction!
var jumpRightAction: SCNAction!
var jumpForwardAction: SCNAction!
var jumpBackwardAction: SCNAction!
複製代碼
在setupActions()
最下方中添加下面代碼:
// 1
let duration = 0.2
// 2
let bounceUpAction = SCNAction.moveBy(x: 0, y: 1.0, z: 0, duration: duration * 0.5)
let bounceDownAction = SCNAction.moveBy(x: 0, y: -1.0, z: 0, duration: duration * 0.5)
// 3
bounceUpAction.timingMode = .easeOut
bounceDownAction.timingMode = .easeIn
// 4
let bounceAction = SCNAction.sequence([bounceUpAction, bounceDownAction])
// 5
let moveLeftAction = SCNAction.moveBy(x: -1.0, y: 0, z: 0, duration: duration)
let moveRightAction = SCNAction.moveBy(x: 1.0, y: 0, z: 0, duration: duration)
let moveForwardAction = SCNAction.moveBy(x: 0, y: 0, z: -1.0, duration: duration)
let moveBackwardAction = SCNAction.moveBy(x: 0, y: 0, z: 1.0, duration: duration)
// 6
let turnLeftAction = SCNAction.rotateTo(x: 0, y: convertToRadians(angle: -90), z: 0, duration: duration, usesShortestUnitArc: true)
let turnRightAction = SCNAction.rotateTo(x: 0, y: convertToRadians(angle: 90), z: 0, duration: duration, usesShortestUnitArc: true)
let turnForwardAction = SCNAction.rotateTo(x: 0, y:
convertToRadians(angle: 180), z: 0, duration: duration, usesShortestUnitArc: true)
let turnBackwardAction = SCNAction.rotateTo(x: 0, y:
convertToRadians(angle: 0), z: 0, duration: duration, usesShortestUnitArc: true)
// 7
jumpLeftAction = SCNAction.group([turnLeftAction, bounceAction, moveLeftAction])
jumpRightAction = SCNAction.group([turnRightAction, bounceAction, moveRightAction])
jumpForwardAction = SCNAction.group([turnForwardAction, bounceAction, moveForwardAction])
jumpBackwardAction = SCNAction.group([turnBackwardAction, bounceAction, moveBackwardAction])
複製代碼
代碼含義:
bounceAction
將向上和向下彈簧效果組成序列;SCNAction.moveBy(x:y:z:duration:)
建立四個方向的移動動做;SCNAction.rotateTo(x:y:z:duration:usesShortestUnitArc:)
建立四個方向的旋轉動做;給ViewController添加handleGesture(_:)
方法:
// 1
func handleGesture(_ sender: UISwipeGestureRecognizer) {
// 2
guard game.state == .playing else {
return
}
// 3
switch sender.direction {
case UISwipeGestureRecognizerDirection.up:
pigNode.runAction(jumpForwardAction)
case UISwipeGestureRecognizerDirection.down:
pigNode.runAction(jumpBackwardAction)
case UISwipeGestureRecognizerDirection.left:
if pigNode.position.x > -15 {
pigNode.runAction(jumpLeftAction)
}
case UISwipeGestureRecognizerDirection.right:
if pigNode.position.x < 15 {
pigNode.runAction(jumpRightAction)
}
default:
break
} }
複製代碼
代碼含義:
在setupGestures()
中添加下面代碼:
let swipeRight = UISwipeGestureRecognizer(target: self,
action: #selector(ViewController.handleGesture(_:)))
swipeRight.direction = .right
scnView.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self,
action: #selector(ViewController.handleGesture(_:)))
swipeLeft.direction = .left
scnView.addGestureRecognizer(swipeLeft)
let swipeForward = UISwipeGestureRecognizer(target: self,
action: #selector(ViewController.handleGesture(_:)))
swipeForward.direction = .up
scnView.addGestureRecognizer(swipeForward)
let swipeBackward = UISwipeGestureRecognizer(target: self,
action: #selector(ViewController.handleGesture(_:)))
swipeBackward.direction = .down
scnView.addGestureRecognizer(swipeBackward)
複製代碼
運行一下,測試手勢控制:
設置遊戲結束時的動做序列
給ViewController添加一個屬性:
var triggerGameOver: SCNAction!
複製代碼
在setupActions()
的最底部添加代碼:
// 1
let spinAround = SCNAction.rotateBy(x: 0, y: convertToRadians(angle:
720), z: 0, duration: 2.0)
let riseUp = SCNAction.moveBy(x: 0, y: 10, z: 0, duration: 2.0)
let fadeOut = SCNAction.fadeOpacity(to: 0, duration: 2.0)
let goodByePig = SCNAction.group([spinAround, riseUp, fadeOut])
// 2
let gameOver = SCNAction.run { (node:SCNNode) -> Void in
self.pigNode.position = SCNVector3(x:0, y:0, z:0)
self.pigNode.opacity = 1.0
self.startSplash()
}
// 3
triggerGameOver = SCNAction.sequence([goodByePig, gameOver])
複製代碼
代碼含義:
goodByePig
;SCNAction.runAction(_:)
類方法容許咱們插入一些邏輯代碼,在block中重設了小豬的位置,透明度,並觸發了startSplash()
方法;triggerGameOver
動做序列,先執行goodByePig
,再執行gameOver
;在stopGame()
方法後面調用一下:
pigNode.runAction(triggerGameOver)
複製代碼
本章節解決如下問題:
這裏咱們用點小技巧來處理小豬與樹林的碰撞問題,使用四個隱藏的節點,當左側節點與樹林碰撞時,就不能再向左移動了:
建立SceneKit Scene File到根目錄下,命名爲Collision.scn,保存在MrPig.scnassets下:
選中Collision.scn,添加一個空節點,命名爲Collision.
拖拽一個Box到場景中,放置在Collision節點下,命名爲Front,位置 (x:0, y:0.25, z:-1).
進入屬性檢查器,設置尺寸爲 (x:0.25, y:0.25, z:0.25).
按住Option和Command,拖拽出另外三個副本,選中一個命名爲Back,位置設爲 (x:0, y:0.25, z:1).
選中另外一個,命名爲Left,位置 (x:-1, y:0.25, z:0)
選中最後一個,命名爲Right,位置 (x:1, y:0.25, z:0)
完成後的效果
接下來,啓用物理屬性 按住Shift選中四個節點,進入物理檢查器,將Type改成Kinematic.
再進入節點檢查器,滾動到Visibility區,設置Opacity爲0.5(供調試),同時取消勾選Casts Shadow.
設置各個節點的位掩碼 Front節點,物理檢查器中,Category mask設爲8.
Back節點,物理檢查器中,Category mask設爲16.
Left節點,物理檢查器中,Category mask設爲32.
Right節點,物理檢查器中,Category mask設爲64.
最後,還要刪除默認的camera.
選中MrPig.scnassets/GameScene.scn,而後拖拽一個Collsion.scn引用節點到場景中.
在ViewController.swift中添加屬性:
var collisionNode: SCNNode!
var frontCollisionNode: SCNNode!
var backCollisionNode: SCNNode!
var leftCollisionNode: SCNNode!
var rightCollisionNode: SCNNode!
複製代碼
在setupNodes()
最後添加下面代碼:
collisionNode = gameScene.rootNode.childNode(withName: "Collision", recursively: true)!
frontCollisionNode = gameScene.rootNode.childNode(withName: "Front", recursively: true)!
backCollisionNode = gameScene.rootNode.childNode(withName: "Back", recursively: true)!
leftCollisionNode = gameScene.rootNode.childNode(withName: "Left", recursively: true)!
rightCollisionNode = gameScene.rootNode.childNode(withName: "Right", recursively: true)!
複製代碼
在ViewController
中添加方法:
func updatePositions() {
collisionNode.position = pigNode.position
}
複製代碼
在ViewController.swift最底部添加方法:
// 1
extension ViewController : SCNSceneRendererDelegate {
// 2
func renderer(_ renderer: SCNSceneRenderer, didApplyAnimationsAtTime time: TimeInterval) {
// 3
guard game.state == .playing else {
return
}
// 4
game.updateHUD()
// 5
updatePositions()
}
}
複製代碼
代碼含義:
SCNSceneRenderDelegate
協議;updatePositions()
,使collisionNode
位置和pigNode
保持一致;記得在setupScenes()
中添加代理:
scnView.delegate = self
複製代碼
運行一下,查看效果:
在ViewController中,定義如下常量:
let BitMaskPig = 1
let BitMaskVehicle = 2
let BitMaskObstacle = 4
let BitMaskFront = 8
let BitMaskBack = 16
let BitMaskLeft = 32
let BitMaskRight = 64
let BitMaskCoin = 128
let BitMaskHouse = 256
複製代碼
接下來,啓動物理效果
選中MrPig.scnassets/MrPig.scn,選中MrPig節點,進入物理檢查器,將Type改成Kinematic.
接着在Bit masks區,將Category mask設爲1,在Physics shape區, 將Type改成Bounding Box並設置Scale爲0.6.
按一樣步驟,選中MrPig.scnassets/Bus.scn,再選中Bus節點,進入物理檢查器,將Type改成Kinematic.
接着在Bit masks區,將Category mask設爲2,在Physics shape區, 將Type改成Bounding Box並設置Scale爲0.8.
選中MrPig.scnassets/Mini.scn,再選中Mini節點,進入物理檢查器,將Type改成Kinematic.
接着在Bit masks區,將Category mask設爲2,在Physics shape區, 將Type改成Bounding Box並設置Scale爲0.8.
選中MrPig.scnassets/SUV.scn,再選中SUV節點,進入物理檢查器,將Type改成Kinematic.
接着在Bit masks區,將Category mask設爲2,在Physics shape區, 將Type改成Bounding Box並設置Scale爲0.8.
選中MrPig.scnassets/TreeLine.scn,再選中TreeLine節點,進入物理檢查器,將Type改成Static.
接着在Bit masks區,將Category mask設爲4,在Physics shape區, 將Type改成Bounding Box並設置Scale爲1.
選中MrPig.scnassets/TreePatch.scn,再選中TreePatch節點,進入物理檢查器,將Type改成Static.
接着在Bit masks區,將Category mask設爲4,在Physics shape區, 將Type改成Bounding Box並設置Scale爲1.
選中MrPig.scnassets/Coin.scn,再選中Coin節點,進入物理檢查器,將Type改成Kinematic.
接着在Bit masks區,將Category mask設爲128,在Physics shape區, 將Type改成Bounding Box並設置Scale爲0.8.
設置接觸掩碼
打開ViewController.swift,在setupNodes()
的底部添加代碼:
// 1
pigNode.physicsBody?.contactTestBitMask = BitMaskVehicle | BitMaskCoin | BitMaskHouse
// 2
frontCollisionNode.physicsBody?.contactTestBitMask = BitMaskObstacle
backCollisionNode.physicsBody?.contactTestBitMask = BitMaskObstacle
leftCollisionNode.physicsBody?.contactTestBitMask = BitMaskObstacle
rightCollisionNode.physicsBody?.contactTestBitMask = BitMaskObstacle
複製代碼
給ViewController添加屬性:
var activeCollisionsBitMask: Int = 0
複製代碼
在ViewContoller.swift最下方添加代碼:
// 1
extension ViewController : SCNPhysicsContactDelegate {
// 2
func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) {
// 3
guard game.state == .playing else {
return
}
// 4
var collisionBoxNode: SCNNode!
if contact.nodeA.physicsBody?.categoryBitMask == BitMaskObstacle {
collisionBoxNode = contact.nodeB
} else {
collisionBoxNode = contact.nodeA
}
// 5
activeCollisionsBitMask |= collisionBoxNode.physicsBody!.categoryBitMask
}
// 6
func physicsWorld(_ world: SCNPhysicsWorld, didEnd contact: SCNPhysicsContact) {
// 7
guard game.state == .playing else {
return
}
// 8
var collisionBoxNode: SCNNode!
if contact.nodeA.physicsBody?.categoryBitMask == BitMaskObstacle {
collisionBoxNode = contact.nodeB
} else {
collisionBoxNode = contact.nodeA
}
// 9
activeCollisionsBitMask &=
~collisionBoxNode.physicsBody!.categoryBitMask
}
}
複製代碼
代碼含義:
SCNPhysicsContactDelegate
協議;physicsWorld(_:didBegin:)
方法;.playing
狀態時的狀況,其餘不處理;activeCollisionsBitMask
中去;physicsWorld(_:didEnd:)
方法,碰撞結束時調用;.playing
狀態;activeCollisionsBitMask
中移除碰撞檢測盒子的類掩碼;在handleGestures(_:)
中的guard
語句後,添加下面代碼:
// 1
let activeFrontCollision = activeCollisionsBitMask & BitMaskFront ==
BitMaskFront
let activeBackCollision = activeCollisionsBitMask & BitMaskBack ==
BitMaskBack
let activeLeftCollision = activeCollisionsBitMask & BitMaskLeft ==
BitMaskLeft
let activeRightCollision = activeCollisionsBitMask & BitMaskRight ==
BitMaskRight
// 2
guard (sender.direction == .up && !activeFrontCollision) ||
(sender.direction == .down && !activeBackCollision) ||
(sender.direction == .left && !activeLeftCollision) ||
(sender.direction == .right && !activeRightCollision) else {
return
}
複製代碼
代碼含義:
guard
來確保沒有碰撞,能夠向該方向移動;最後,在setupScenes()
中添加代理:
gameScene.physicsWorld.contactDelegate = self
複製代碼
如今運行一下,小豬就不會再跳進樹林中了:
處理和車輛的碰撞
在physicsWorld(_:didBegin:)
中最後添加下面代碼:
// 1
var contactNode: SCNNode!
if contact.nodeA.physicsBody?.categoryBitMask == BitMaskPig {
contactNode = contact.nodeB
} else {
contactNode = contact.nodeA
}
// 2
if contactNode.physicsBody?.categoryBitMask == BitMaskVehicle {
stopGame()
}
複製代碼
代碼含義:
處理和金幣的碰撞
在physicsWorld(_:didBegin:)
中的後面添加下面代碼:
// 1
if contactNode.physicsBody?.categoryBitMask == BitMaskCoin {
// 2
contactNode.isHidden = true
contactNode.runAction(SCNAction.waitForDurationThenRunBlock(duration:
60) { (node: SCNNode!) -> Void in
node.isHidden = false
})
// 3
game.collectCoin()
}
複製代碼
代碼含義:
運行遊戲,如今能夠收集金幣了
更新攝像機位置
打開ViewController.swift,在updatePositions()
在最底部,添加下面的代碼:
let lerpX = (pigNode.position.x - cameraFollowNode.position.x) * 0.05
let lerpZ = (pigNode.position.z - cameraFollowNode.position.z) * 0.05
cameraFollowNode.position.x += lerpX
cameraFollowNode.position.z += lerpZ
複製代碼
這段代碼讓攝像機朝小豬方向慢慢移動.
更新燈光位置 在updatePositions()
在最底部,添加下面的代碼:
lightFollowNode.position = cameraFollowNode.position
複製代碼
更新交通情況 咱們須要用幾輛車來模擬不斷的交通狀況,因此當小車遇到邊界時,須要從新設定它們的位置. 在ViewController中,添加下面的方法:
func updateTraffic() {
// 1
for node in trafficNode.childNodes {
// 2
if node.position.x > 25 {
node.position.x = -25
} else if node.position.x < -25 {
node.position.x = 25
}
} }
複製代碼
而後還要在renderer(_:didApplyAnimationsAtTime:)
底部添加調用:
updateTraffic()
複製代碼
參考下圖:
physicsWorld(_:didBegin:)
中添加代碼,讓Mr.Pig把金幣放到家中;if contactNode.physicsBody?.categoryBitMask == BitMaskHouse {
if game.bankCoins() == true {
}
}
複製代碼
在ViewController.swift中,給setupSounds()
中添加下面代碼:
// 1
if game.state == .tapToPlay {
// 2
let music = SCNAudioSource(fileNamed: "MrPig.scnassets/Audio/
Music.mp3")!
// 3
music.volume = 0.3;
music.loops = true
music.shouldStream = true
music.isPositional = false
// 4
let musicPlayer = SCNAudioPlayer(source: music)
// 5
splashScene.rootNode.addAudioPlayer(musicPlayer)
}
複製代碼
此外,還要再添加一些環境音,在setupSounds()
底部再添加:
// 1
else if game.state == .playing {
// 2
let traffic = SCNAudioSource(fileNamed: "MrPig.scnassets/Audio/
Traffic.mp3")!
traffic.volume = 0.3
traffic.loops = true
traffic.shouldStream = true
traffic.isPositional = true
// 3
let trafficPlayer = SCNAudioPlayer(source: traffic)
gameScene.rootNode.addAudioPlayer(trafficPlayer)
// 4
game.loadSound(name: "Jump", fileNamed: "MrPig.scnassets/Audio/
Jump.wav")
game.loadSound(name: "Blocked", fileNamed: "MrPig.scnassets/Audio/
Blocked.wav")
game.loadSound(name: "Crash", fileNamed: "MrPig.scnassets/Audio/
Crash.wav")
game.loadSound(name: "CollectCoin", fileNamed: "MrPig.scnassets/Audio/
CollectCoin.wav")
game.loadSound(name: "BankCoin", fileNamed: "MrPig.scnassets/Audio/
BankCoin.wav")
}
複製代碼
代碼含義:
.Playing
狀態;最後再添加一些音效 跳躍音效:在handleGesture(_:)
方法後面添加:
game.playSound(node: pigNode, name: "Jump")
複製代碼
遇到障礙物音效:在第二個guard
語句中:
game.playSound(node: pigNode, name: "Blocked")
複製代碼
收集金幣音效:在physicsWorld(_:didBegin:)
中的game.collectCoin()
語句後,添加:
game.playSound(node: pigNode, name: "CollectCoin")
複製代碼
存放金幣音效:在physicsWorld(_:didBegin:)
中if game.bankCoins() == true
語句後面添加:
game.playSound(node: pigNode, name: "BankCoin")
複製代碼
被車撞音效:在physicsWorld(_:didBegin:)
中stopGame()
以前添加:
game.playSound(node: pigNode, name: "Crash")
複製代碼
運行一下, 完成了!!