Search code examples
swiftcollision-detectiongame-physicsscenekit

SceneKit dynamic object falls through static floor


I have a SceneKit game in swift and in it I have a car with a dynamic physics body that is set up like this:

let carScene = SCNScene(named: "art.scnassets/truck.scn")!
    let carNode = carScene.rootNode.childNode(withName: "Cube", recursively: true)!



   let carPhysicsBody = SCNPhysicsBody(type: .dynamic,shape: SCNPhysicsShape(geometry: SCNBox(width: 5.343, height: 12.125, length: 4.373, chamferRadius: 0)))

    carPhysicsBody.mass = 3
    carPhysicsBody.friction = 2
    carPhysicsBody.contactTestBitMask = 1
    carNode.physicsBody = carPhysicsBody
    carNode.position = SCNVector3(x: 0, y: 0, z: 5)
    carNode.physicsBody?.applyForce(SCNVector3(x: 0, y: 50, z: 0), asImpulse: true)

    car = carNode
    floorScene.rootNode.addChildNode(car)

The floor's physics looks like this:

enter image description here

As you can see the car gets launched into the air. Then the gravity in the scene makes it fall, and instead of colliding with the floor, it goes right through it.

The gravity looks like this:

What should I change so it will collide with the floor?


Solution

  • I've made a sample macOS playground, available at github.com/heckj/scenekit-physics-playground that shows a physics body interacting. I suspect the core of the problem in your local example is that the floor object doesn't actually have an SCNPhysicsBody associated with it. Until I explicitly set it on SCNFloor (as static), the text blob "fell through" as you originally described.

    I recommend adding sceneView.debugOptions = [.showPhysicsShapes] to see the relevant debugging shapes. I've made (and pushed) a few updates to the above repo. Using stock SCNFloor to establish geometry for the physics collection made a tiny target (which is why the slight horizontal impulse made it appear to "pass through"). This last update sets the floor geometry to a long, wide, thin box.