SceneKit物理模拟与实际的Node位置不匹配

时间:2017-10-26 01:34:10

标签: ios swift scenekit

我正在尝试在Scenekit中实现第一人称太空射击游戏,而我(熟悉的,我知道)让物理模拟与SCNNodes的实际位置和变换相匹配的问题是物理模拟应该代表的

敌方无人机舰船是使用此功能创建的,它将节点放置在名为SectorObjectNode的SCNnode中,其中包含船外的所有游戏对象(敌人,星星等)及其鱼雷(两者都存在于场景中&# 39; s根节点:

func spawnDrone(_ sender: UIButton) {

    let humonshipScene = SCNScene(named: "Humon.scn")
    let humonShip = humonshipScene?.rootNode.childNodes[0]
    self.enemyDrone = humonShip
    let droneShape = SCNBox(width: 10, height: 5, length: 5, chamferRadius: 0)
    let dronePhysicsShape = SCNPhysicsShape(geometry: droneShape, options: nil)
    self.enemyDrone?.physicsBody = SCNPhysicsBody(type: .dynamic, shape: dronePhysicsShape)
    self.enemyDrone?.physicsBody?.isAffectedByGravity = false
    self.enemyDrone?.physicsBody?.friction = 0
    self.enemyDrone?.physicsBody?.categoryBitMask = 0b00000010
    self.enemyDrone?.physicsBody?.contactTestBitMask = 0b00000010
    self.enemyDrone?.name = "drone"
    self.enemyDrone?.pivot = SCNMatrix4MakeTranslation(0.5, 0.5, 0.5)
    self.enemyDrone?.position = SCNVector3Make(0, 0, -30)
    self.enemyDrone?.scale = SCNVector3Make(1, 1, 1)
    let actualPosition = self.scene.rootNode.convertPosition((self.enemyDrone?.position)!, from: self.enemyDrone)
    self.enemyDrone?.position = self.scene.rootNode.convertPosition(actualPosition, to: self.sectorObjectsNode)
    self.sectorObjectsNode.addChildNode(self.enemyDrone!)
}

使用以下代码旋转扇区对象节点以响应onScreen操纵杆(从而旋转"宇宙"在船周围模拟运动):

func turnShip() {
    self.rotate(self.sectorObjectsNode, around: SCNVector3Make(1, 0, 0), by: CGFloat(self.yThrust))
    self.rotate(self.sectorObjectsNode, around: SCNVector3Make(0, 1, 0), by: CGFloat(self.xThrust))

}

func rotate(_ node: SCNNode, around axis: SCNVector3, by angle: CGFloat) {
    let rotation = SCNMatrix4MakeRotation(Float(angle), axis.x, axis.y, axis.z)
    let newTransform = SCNMatrix4Mult(node.worldTransform, rotation)

    // Set the new transform
    if let parent = node.parent {
        node.transform = parent.convertTransform(newTransform, from: nil)
    } else {
        node.transform = newTransform
    }
}

但是此代码会导致物理模拟重置(当sceneView.debugOptions设置为.showPhysicsShapes时,屏幕中心的灰色框是无人机的物理边界框,如引擎所示),结果如下:

Physics bounding Box not following object

我试图在旋转之前捕捉无人机的演示位置,然后在两个旋转功能之后应用它,但这会导致船向下和向左移动。关于如何让无人机的物理模拟(我专门用于碰撞检测)能够坚持敌人尸体节点的实际位置,我受到了阻碍。

1 个答案:

答案 0 :(得分:2)

按照惯例,问题是RTFM。我将物理体设置为错误的类型:

self.enemyDrone?.physicsBody = SCNPhysicsBody(type: .dynamic, shape: dronePhysicsShape)

需要更改为

self.enemyDrone?.physicsBody = SCNPhysicsBody(type: .kinematic, shape: dronePhysicsShape)