如何将物理添加到 SceneKit 场景?

how to add physics to the SceneKit scene?

嘿,我有一个场景套件场景,我的目标只是让场景中的 guy/character 因重力而落下,然后撞到地板上。而已。 "Guy" 是一个简单的节点 .scn 节点。地面也是一个 .scn 场景,如下面的代码所示。我已经掌握了我必须尝试向场景添加简单物理的技能。我知道如何在 SPRITEKIT 中完美地添加物理特性,但是 .scn 节点不允许我附加用于赋予角色物理特性的相同变量。此代码中没有错误但是字符在 运行 时不受重力影响,谢谢

代码:

   // Collision bit masks
  let BitmaskCollision        = 1 << 2
  let BitmaskCollectable      = 1 << 3
  let BitmaskEnemy            = 1 << 4
  let BitmaskFriend           = 1 << 5
  let BitmaskOutofBounds      = 1 << 6

  class GameViewController: UIViewController, ADBannerViewDelegate, SKPhysicsContactDelegate, SKSceneDelegate, SCNSceneRendererDelegate, SCNPhysicsContactDelegate{

// The character
let character = Character()

// The Playing Fields
let FieldScene = SCNScene(named: "art.scnassets/TesingCampusField.dae")!


   override func viewDidLoad() {
    super.viewDidLoad()

    let scnView = self.view as! SCNView
    scnView.scene = FieldScene
    scnView.playing = true
    scnView.delegate = self
    scnView.scene!.physicsWorld.contactDelegate = self
    //-----Adding Gravity----------------------------------------------
    scnView.scene!.physicsWorld.gravity = SCNVector3(x: 0, y: 0, z: -9.8)
    //------Add-the-Character-to-Scene--------------------
    scnView.scene!.rootNode.addChildNode(character.node)

     }

此控制器的代码结束 角色只是从一个名为 "Character"

的文件中设置的
class Character {

let node = SCNNode()

init() {
    let GuyScene = SCNScene(named: "art.scnassets/Guy.scn")
    let characterTopLevelNode: SCNNode = GuyScene!.rootNode.childNodeWithName("Guy", recursively: true)!
    node.addChildNode(characterTopLevelNode)


   characterTopLevelNode.physicsBody?.contactTestBitMask = BitmaskEnemy    
    characterTopLevelNode.physicsBody?.collisionBitMask = BitmaskCollision
    characterTopLevelNode.physicsBody?.categoryBitMask = BitmaskCollectable
    characterTopLevelNode.physicsBody?.affectedByGravity = true
    characterTopLevelNode.physicsBody?.friction = 0
    characterTopLevelNode.physicsBody?.restitution = 0
    characterTopLevelNode.physicsBody?.angularDamping = 0

    // Below is the Creation of the Physics body of the character
    let (min, max) = node.boundingBox
    let collisionCapsuleRadius = CGFloat(max.x - min.x) * 0.4
    let collisionCapsuleHeight = CGFloat(max.y - min.y)
    let characterCollisionNode = SCNNode()
    characterCollisionNode.name = "collider"

    // position light above the floor so you dont hit it and cause a contact
    characterCollisionNode.position = SCNVector3(0.0, collisionCapsuleHeight * 0.51, 0.0)
    characterCollisionNode.physicsBody = SCNPhysicsBody(type: .Dynamic, shape:SCNPhysicsShape(geometry: SCNCapsule(capRadius: collisionCapsuleRadius, height: collisionCapsuleHeight), options:nil))
    // Adding the Pysics body of the character called "characterCollisionNode" to the actually character
    node.addChildNode(characterCollisionNode)
      }
     }

这似乎是这个问题的早期版本

答案可能相似,您似乎没有将 node 添加为场景的子项。