阅读 278

18-《ARKit by Tutorials》读书笔记5:特殊物理效果

ARKit系列文章目录

本文是Ray Wenderlich上《ARKit by Tutorials》的读书笔记,主要讲内容概要和读后感  

本文中,我们将通过一个Monster Truck小游戏的例子,学习SceneKit中的一些特殊的物理效果.你一定不知道:SceneKit中内置了正宗的车辆物理效果!

基本结构

共三部分:车身(Body),车轴(Axle),车轮(Wheel)

在SceneKit的编辑器中进行组装:

注意,车轮是通过一个轴来连接到真正的车轴(Axle)上的.

在代码中加载这些部件:

// 1 
let truckScene = SCNScene(
  named: "MonsterTruck.scnassets/Models/MonsterTruck.scn")!
truckNode = truckScene.rootNode.childNode(
  withName: "Truck", recursively: true)
wheelFLNode = truckScene.rootNode.childNode(
  withName: "Wheel_FL", recursively: true)
wheelFRNode = truckScene.rootNode.childNode(
  withName: "Wheel_FR", recursively: true)
wheelRLNode = truckScene.rootNode.childNode(
  withName: "Wheel_RL", recursively: true)
wheelRRNode = truckScene.rootNode.childNode(
  withName: "Wheel_RR", recursively: true)
// 2  
truckNode.addChildNode(wheelFLNode!)
truckNode.addChildNode(wheelFRNode!)
truckNode.addChildNode(wheelRLNode!)
truckNode.addChildNode(wheelRRNode!)
// 3
truckNode.isHidden = true
sceneView.scene.rootNode.addChildNode(truckNode)
复制代码

添加车辆物理效果

SceneKit中有专用的物理效果:

  • SCNPhysicsVehicle:让一个标准的物理形体表现的像一辆车.
  • SCNPhysicsBody:正常情况下的标准物理形体.用在车身类物体上.这类形体在创建过程中将会是SCNPhysicsVehicle类型的.
  • SCNPhysicsVehicleWheel:专用的物理形体,不仅模拟车轮的行为,还有外观及其他物理特性.这类形体在创建过程中将会是SCNPhysicsVehicle类型的.

选中Truch节点,做如下图设置:

创建车轮物理效果

定义一些常量,交赋值给SCNPhysicsVehicleWheel节点.

let wheelRadius: CGFloat = 0.04
let wheelFrictionSlip: CGFloat = 0.9
let suspensionMaxTravel: CGFloat = 4.0
let suspensionMaxForce: CGFloat = 100
let suspensionRestLength: CGFloat = 0.08
let suspensionDamping: CGFloat = 2.0
let suspensionStiffness: CGFloat = 2.0
let suspensionCompression: CGFloat = 4.0

func createPhysicsVehicleWheel(wheelNode: SCNNode,
  position: SCNVector3) -> SCNPhysicsVehicleWheel {
  let wheel = SCNPhysicsVehicleWheel(node: wheelNode)
  wheel.connectionPosition = position
  wheel.axle = SCNVector3(x: -1.0, y: 0, z: 0)
  wheel.maximumSuspensionTravel = suspensionMaxTravel
  wheel.maximumSuspensionForce = suspensionMaxForce
  wheel.suspensionRestLength = suspensionRestLength
  wheel.suspensionDamping = suspensionDamping
  wheel.suspensionStiffness = suspensionStiffness
  wheel.suspensionCompression = suspensionCompression
  wheel.radius = wheelRadius
  wheel.frictionSlip = wheelFrictionSlip
  return wheel
}
复制代码

各个常量的含义:

  • Wheel Radius(车轮半径):车轮物理外观的实际半径.
  • Wheel Friction Slip(车轮摩擦滑动): 指定车轮自身和接触表面的摩擦力(个人理解就是最大静摩擦力,超过后会打滑).
  • Suspension Maximum Travel(悬架最大行程): 定义了车轮允许沿连接点上下移动的最大行程.单位是厘米.
  • Suspension Maximum Force(悬架最大受力): 定义悬架受到的车轮和车身的最大受力.单位是牛顿.
  • Suspension Rest Length(悬架静息长度): 定义悬架在静止不动时的长度.单位是米.
  • Suspension Damping(悬架阻尼): 定义了悬架在振荡中的阻尼系数.
  • Suspension Stiffness(悬架刚度). 定义了车轮自身和车辆底盘之间的弹簧系数.
  • Suspension Compression(悬架压缩回弹): 定义了悬架在受到压缩后,回到静息状态的速度.

全车的物理效果

将车轮绑定在车身上,并使用物理效果:

func createVehiclePhysics() {
  // 1
  if physicsVehicle != nil {
    sceneView.scene.physicsWorld.removeBehavior(physicsVehicle)
  }
  //2 
  let wheelFL = createPhysicsVehicleWheel(
    wheelNode: wheelFLNode!,
    position: SCNVector3(x: -0.07, y: 0.04, z: 0.06))
  let wheelFR = createPhysicsVehicleWheel(
    wheelNode: wheelFRNode!,
    position: SCNVector3(x: 0.07, y: 0.04, z: 0.06))
  let wheelRL = createPhysicsVehicleWheel(
    wheelNode: wheelRLNode!,
    position: SCNVector3(x: -0.07, y: 0.04, z: -0.06))
  let wheelRR = createPhysicsVehicleWheel(
    wheelNode: wheelRRNode!,
    position: SCNVector3(x: 0.07, y: 0.04, z: -0.06))
  // 3     
  physicsVehicle = SCNPhysicsVehicle(
    chassisBody: truckNode.physicsBody!,
    wheels: [wheelFL, wheelFR, wheelRL, wheelRR])
  // 4
  sceneView.scene.physicsWorld.addBehavior(physicsVehicle)
}
复制代码

初始化时放置的位置,将车辆放在聚焦框focusNode的上面:

func updatePositions() {
  // 1
  self.truckNode.position = self.focusNode.position
  self.truckNode.position.y += 0.20
  
  // 2
  self.truckNode.physicsBody?.velocity = SCNVector3Zero
  self.truckNode.physicsBody?.angularVelocity = SCNVector4Zero
  
  // 3
  self.truckNode.physicsBody?.resetTransform()
}
复制代码

此外,还有添加地面,设置游戏状态等.

添加引擎的力

我们想让用户点击屏幕时,加速前进,松开后缓慢减速

var maximumSpeed: CGFloat = 2.0

var isThrottling = false
var engineForce: CGFloat = 0
let defaultEngineForce: CGFloat = 10.0

var brakingForce: CGFloat = 0
let defaultBrakingForce: CGFloat = 0.01

override func touchesBegan(_ touches: Set<UITouch>,
  with event: UIEvent?) {
  isThrottling = true
}
    
override func touchesEnded(_ touches: Set<UITouch>,
  with event: UIEvent?) {
  isThrottling = false
}
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
    DispatchQueue.main.async {
     self.updateStatus()
     self.updateFocusNode()
     self.updateVehiclePhysics()
   }
}
  
func updateVehiclePhysics() {
  // 1
  guard self.gameState == .playGame else { return }
  // 2
  if isThrottling {
   engineForce = defaultEngineForce
   brakingForce = 0
 } else {
   engineForce = 0
   brakingForce = defaultBrakingForce
 }
  // 3 apply方法是SCNPhysicsVehicle自带的方法
  physicsVehicle.applyEngineForce(engineForce, forWheelAt: 0)
  physicsVehicle.applyEngineForce(engineForce, forWheelAt: 1)
  physicsVehicle.applyEngineForce(engineForce, forWheelAt: 2)
  physicsVehicle.applyEngineForce(engineForce, forWheelAt: 3)    

  physicsVehicle.applyBrakingForce(brakingForce, forWheelAt: 0)
  physicsVehicle.applyBrakingForce(brakingForce, forWheelAt: 1)
  physicsVehicle.applyBrakingForce(brakingForce, forWheelAt: 2)
  physicsVehicle.applyBrakingForce(brakingForce, forWheelAt: 3)

    // Limit Speed
    if self.physicsVehicle.speedInKilometersPerHour >
      CGFloat(maximumSpeed) {
      engineForce = CGFloat(0.0)
    }
}
复制代码

控制方向

可以用CoreMotion框架来控制车辆方向.

let motionManager = CMMotionManager()
let steeringClamp: CGFloat = 0.6
var steeringAngle: CGFloat = 0


func updateSteeringAngle(acceleration: CMAcceleration) {
  steeringAngle = (CGFloat)(acceleration.y)
  
  if steeringAngle < -steeringClamp {
    steeringAngle = -steeringClamp;
  } else if steeringAngle > steeringClamp {
    steeringAngle = steeringClamp;
  }
}

func startAccelerometer() {
  // 1
  guard motionManager.isAccelerometerAvailable else { return }
  // 2
  motionManager.accelerometerUpdateInterval = 1/60.0
  // 3
  motionManager.startAccelerometerUpdates(
    to: OperationQueue.main,
    withHandler: { (accelerometerData: CMAccelerometerData?,
      error: Error?) in
      self.updateSteeringAngle(acceleration:
        accelerometerData!.acceleration)
  })
}


func stopAccelerometer() {
  motionManager.stopAccelerometerUpdates()
}
复制代码

此外,还要在updateVehiclePhysics()方法中添加,才能使用,这也是系统自带的处理车辆转向的方法:

physicsVehicle.setSteeringAngle(steeringAngle, forWheelAt: 0)
physicsVehicle.setSteeringAngle(steeringAngle, forWheelAt: 1)
复制代码

第五部分读书笔记结束!请期待第二版的读书笔记。

ARKit是在WWDC2017上推出的,2018春季更新了ARKit 1.5版本.《ARKit by Tutorials》第一版写作完成时,WWDC2018还未召开,因此第一版书中内容较为简单,也没有涉及到ARKit 2.0的新特性:世界地图,图片追踪,3D物体检测等.
后续第二版更新已在2018年秋季发布,新增了两章ARKit 2.0的Demo及讲解,我会持续更新该读书笔记系列.

关注下面的标签,发现更多相似文章
评论