[SceneKit專題]24-體素風格過馬路遊戲Mr. Pig

說明

本系列文章是對<3D Apple Games by Tutorials>一書的學習記錄和體會node

此書對應的代碼地址git

SceneKit系列文章目錄github

更多iOS相關知識查看github上WeekWeekUpProjectswift

效果以下: app

項目中用到的模型是用MagicaVoxel建立的,能夠到ephtracy.github.io上去免費下載.使用教程參見本系列其餘文章.編輯器

19-Transitions轉場

建立項目

建立項目,選擇iOS > Application > Single View Application模板. ide

更改設置,只保留豎直方向:oop

添加資源文件: 拖拽resources/GameUtils/文件夾到項目中,選擇Group: post

拖拽resources/MrPig.scnassets文件夾到項目中,選擇Create folder references:學習

完成後的效果:

添加應用圖標和啓動屏幕 在resources文件夾下找到LaunchScreenAppIcon文件夾,拖拽到對應地方去:

給啓動屏幕添加圖片約束:

打開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.pngScene Background屬性:

爲了讓背景更好看,設置出太陽般的放射光暈效果,須要拖拽一個Plane節點到場景中,命名爲Rays,設置位置 (x:0, y:0.25, z:-1),可見度Visibility Opacity0.25:

打開屬性檢查器,設置Size(x:5, y:5),並設置圓角半徑Corner Radius2.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和點擊開始節點

  • The Logo node:使用Plane類型節點,MrPigLogo_Diffuse.png貼圖,設置尺寸爲width:1, height:0.5,位置設置爲 (x:0, y:1, z:0.5),注意不要受到燈光的影響,作法參考Rays節點.
  • The TapToPlay node:使用Plane類型節點,TapToPlay_Diffuse.png貼圖,設置尺寸爲width:1, height:0.25,位置設置爲 (x:0, y:-0.3, z:0.5),注意不要受到燈光的影響,作法參考Rays節點.

加載並展現閃屏界面

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()
  }
}
複製代碼

運行後,點擊屏幕開始遊戲了.

20-Advanced Scene Creation高級場景建立

添加主角

選中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)!
複製代碼

代碼含義:

  1. 將cameraNode綁定到camera上,而後將hudNode添加上去做爲子節點,這樣HUD就能一直顯示在鏡頭前了.
  2. 將cameraFollowNode綁定到FollowCamera上,這樣只須要更新其位置,攝像機就能一直跟隨着小豬了.

在場景樹中點擊+號添加一個空節點,在節點檢查器中,將其命名爲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)!
複製代碼

接着,須要複製一下達到下面的效果:

  • 左側車道是公交車道,右側車道是較小較快的車道;
  • 兩條公路,一條朝左開,一條朝右開;
  • 按住Option鍵來快速複製;
  • 按住Command鍵來與周圍元素對齊;
  • 兩車之間就留下足夠距離讓小豬能行;
  • 完成一條公路後,選中全部車輛,並按住Option拖拽到另外一條公路上,就複製完成了,而後再掉轉180度;
  • 旋轉車輛時,按住Command鍵能夠更方便地對齊;

完成後,運行一下:

添加樹林

拖拽一個空的SceneKit Scene File,命名爲TreeLine並放置在MrPig.scnassets目錄下:

TreeLine.scn中,建立一個空節點,命名爲TreeLine,它將做爲父容器節點:

按下面的圖來擺放各類樹木:

  • X:表明在x軸上的座標;
  • Z:表明在z軸上的座標;
  • S:表明小的樹SmallTree;
  • M:表明中等樹MediumTree;
  • L:表明大的樹LargeTree;

例如左上角第一個,放置一個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處樹林座標爲:

  • Position:(x:0,y:0,z:7),Euler:(x:0,y:0,z:0).
  • Position:(x:-7, y:0, z:3), Euler: (x:0, y:90, z:0).
  • Position:(x:7,y:0,z:3),Euler:(x:0,y:90,z:0).
  • Position:(x:-14,y:0,z:-1),Euler:(x:0,y:0,z:0).
  • Position:(x:14,y:0,z:-1),Euler:(x:0,y:0,z:0).

公路中間處的座標爲:

  • Position:(x:-14,y:0,z:-8),Euler:(x:0,y:0,z:0).
  • Position:(x:14,y:0,z:-8),Euler:(x:0,y:0,z:0).

後面部分的座標爲:

  • Position:(x:18,y:0,z:-19),Euler:(x:0,y:90,z:0).
  • Position:(x:-18,y:0,z:-19),Euler:(x:0,y:90,z:0).
  • Position:(x::-11,y:0,z:-23),Euler:(x:0,y:0,z:0).
  • Position: (x:0, y:0, z:-23), Euler:(x:0, y:0, z:0).
  • Position:(x:11,y:0,z:-23),Euler:(x:0,y:0,z:0).

按下圖來擺放樹林TreePatch:

放置座標以下:

  • Position:(x:10,y:0,z:-17),Euler:(x:0,y:0,z:0).
  • Position:(x:-10,y:0,z:-17),Euler:(x:0,y:0,z:0).
  • Position:(x:0,y:0,z:-17),Euler:(x:0,y:90,z:0).
添加金幣

先建立一個空節點,命名爲Coins,做爲金幣的容器節點:

而後拖拽Coin引用節點到場景中,座標以下:

  • Position:(x:0,y:0.5,z:-8).
  • Position:(x:0,y:0.5,z:-21).
  • Position:(x:-14,y:0.5,z:-20).
  • Position:(x:14,y:0.5,z:-20).

完成後,效果如圖:

21-Actions動做

動做編輯器

背景射線動起來 打開MrPig.scnassets/SplashScene.scn,選中Rays.拖拽一個Rotate Action,在屬性檢查器中設置時長30,z軸360;

右鍵點擊,建立循環,點擊

金幣動畫

選中MrPig.scnassets/Coin.scn,按順序拖拽兩個Move Action,再並排放置一個Rotate Action

選中第一個Move Action,設置Start Time0,Duration0.5.設置Timing FunctionEase In, Ease Out, 設置Offset(x:0, y:0.5, z:0).

選中第二個Move Action,設置Start Time0.5,Duration0.5.設置Timing FunctionEase In, Ease Out, 設置Offset(x:0, y:-0.5, z:0).

選中Move Action,設置Start Time0,Duration1.設置Timing FunctionLinear, 設置Euler Angle(x:0, y:360, z:0).

Shift選中所有,而後右鍵單擊,建立循環

讓閃屏頁面的小豬動起來 進入MrPig.scnassets/SplashScreen.scn,選中MrPig,建立一系列旋轉動做:

  1. 鏈接7個Rotate Actions序列,設置時長爲0.25s;
  2. 設置第一個旋轉動做,讓它沿x軸旋轉30度;
  3. 設置下一個,沿x軸旋轉-30度;
  4. 重複設置接下來的幾個動做,直到最後一個;
  5. 最後一個動做是沿y軸旋轉180度,讓小豬秀它的尾巴;
  6. 移動遊標,預覽動做,會看到小豬搖頭晃腦,而後轉身給你看尾巴;
  7. 設置循環播放

運行一下,查看動做:

代碼建立動做

交通動做 打開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])
複製代碼

代碼含義:

  1. 定義時長;
  2. 向上,向下的彈簧效果;
  3. 修改時間模式,一個漸入,一個漸出;
  4. 建立bounceAction將向上和向下彈簧效果組成序列;
  5. SCNAction.moveBy(x:y:z:duration:)建立四個方向的移動動做;
  6. SCNAction.rotateTo(x:y:z:duration:usesShortestUnitArc:)建立四個方向的旋轉動做;
  7. 按順序組合出四個跳躍動做;
添加移動手勢

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
} }
複製代碼

代碼含義:

  1. 定義一個手勢方法;
  2. 判斷遊戲狀態;
  3. 判斷手勢方向,左右限制不能超出範圍;

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])
複製代碼

代碼含義:

  1. 建立一些基本動做:一個旋轉720度,一個向上移動,一個逐漸透明;共同組成了一個動做組,叫goodByePig;
  2. SCNAction.runAction(_:)類方法容許咱們插入一些邏輯代碼,在block中重設了小豬的位置,透明度,並觸發了startSplash()方法;
  3. 建立最終的triggerGameOver動做序列,先執行goodByePig,再執行gameOver;

stopGame()方法後面調用一下:

pigNode.runAction(triggerGameOver)
複製代碼

22-Advanced Collision Detection高級碰撞檢測

本章節解決如下問題:

  • 小豬遇到障礙時不能中止,如撞上樹木;
  • 小豬撞到汽車不能結束遊戲;
  • 小豬沒法真正收集金幣;
隱藏的碰撞檢測幾何體

這裏咱們用點小技巧來處理小豬與樹林的碰撞問題,使用四個隱藏的節點,當左側節點與樹林碰撞時,就不能再向左移動了:

建立隱藏的碰撞節點

建立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).

按住OptionCommand,拖拽出另外三個副本,選中一個命名爲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()
  }
}
複製代碼

代碼含義:

  1. 實現了SCNSceneRenderDelegate協議;
  2. 在渲染循環中剛剛完成動畫和動做後,插入遊戲邏輯;
  3. 判斷遊戲狀態;
  4. 更新HUD;
  5. 調用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並設置Scale0.6.

按一樣步驟,選中MrPig.scnassets/Bus.scn,再選中Bus節點,進入物理檢查器,將Type改成Kinematic.

接着在Bit masks區,將Category mask設爲2,在Physics shape區, 將Type改成Bounding Box並設置Scale0.8.

選中MrPig.scnassets/Mini.scn,再選中Mini節點,進入物理檢查器,將Type改成Kinematic.

接着在Bit masks區,將Category mask設爲2,在Physics shape區, 將Type改成Bounding Box並設置Scale0.8.

選中MrPig.scnassets/SUV.scn,再選中SUV節點,進入物理檢查器,將Type改成Kinematic.

接着在Bit masks區,將Category mask設爲2,在Physics shape區, 將Type改成Bounding Box並設置Scale0.8.

選中MrPig.scnassets/TreeLine.scn,再選中TreeLine節點,進入物理檢查器,將Type改成Static.

接着在Bit masks區,將Category mask設爲4,在Physics shape區, 將Type改成Bounding Box並設置Scale1.

選中MrPig.scnassets/TreePatch.scn,再選中TreePatch節點,進入物理檢查器,將Type改成Static.

接着在Bit masks區,將Category mask設爲4,在Physics shape區, 將Type改成Bounding Box並設置Scale1.

選中MrPig.scnassets/Coin.scn,再選中Coin節點,進入物理檢查器,將Type改成Kinematic.

接着在Bit masks區,將Category mask設爲128,在Physics shape區, 將Type改成Bounding Box並設置Scale0.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
  }
    
}
複製代碼

代碼含義:

  1. 添加類擴展,遵照SCNPhysicsContactDelegate協議;
  2. 實現physicsWorld(_:didBegin:)方法;
  3. 只須要關注.playing狀態時的狀況,其餘不處理;
  4. 判斷哪一個是障礙物,哪一個是隱藏的碰撞檢測盒子;
  5. 用位運算OR,將碰撞檢測盒子的類掩碼添加到activeCollisionsBitMask中去;
  6. 實現physicsWorld(_:didEnd:)方法,碰撞結束時調用;
  7. 判斷.playing狀態;
  8. 判斷哪一個是障礙物,哪一個是隱藏的碰撞檢測盒子;
  9. 用位運算符NOT和位運算符AND,從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
}
複製代碼

代碼含義:

  1. 用位運算符AND來判斷四個方向的隱藏節點是否已經發生了碰撞;
  2. 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()
}
複製代碼

代碼含義:

  1. 和前面相似,用來判斷哪一個是小豬;
  2. 若是是和車輛碰撞,就結束遊戲;

處理和金幣的碰撞

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()
}
複製代碼

代碼含義:

  1. 若是是和金幣碰撞;
  2. 隱藏金幣,並在60秒後從新出現;
  3. 收集金幣,增長分數;

運行遊戲,如今能夠收集金幣了

23-Audio音頻

結束處理

更新攝像機位置

打開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()
複製代碼
設置房屋
  1. 建立一個新SceneKit場景,命名爲Home.scn,並刪除默認的攝像機;
  2. 添加一個House.scn到場景中,放在正中間;
  3. 建立一個空的節點,命名爲Obstacles,用來做爲容器節點;
  4. 添加一些樹;
  5. 添加一個Mini.scn;

參考下圖:

  1. 周圍的障礙物Obstacles須要設置物理形體;分類掩碼category bit mask設置爲4.而House的掩碼設置爲256;
  2. 完成後,引入到遊戲場景中;
  3. 最後,在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")
}
複製代碼

代碼含義:

  1. 檢查是不是.Playing狀態;
  2. 設置MrPig.scnassets/Audio/Traffic.mp3做爲流音頻的源;
  3. 添加到時根節點時開始播放音頻源;
  4. 預加載其餘用到的音效;

最後再添加一些音效 跳躍音效:在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")
複製代碼

運行一下, 完成了!!

相關文章
相關標籤/搜索