Search code examples
swiftcollision-detectiongame-physicsscenekitscnnode

SceneKit – Making a custom physics body


So I've designed a hallway that I want my player to walk through, but I can 't seem to get a physics body to work for it. Either the player walks through the walls or he can't walk down the hallway because it sees the object as a giant cube. How do I get the physics body to go around the object.

let chessPieces = SCNScene(named: "art.scnassets/hallway.dae")

if let knight2 = chessPieces?.rootNode.childNodeWithName("Room", recursively: true) {

    knight2.position = SCNVector3Make(150, 30, 0)
    knight2.scale = SCNVector3Make(knight2.scale.x * 200, knight2.scale.y * 200, knight2.scale.z * 200)            
    var nodeScale = NSValue(SCNVector3:SCNVector3Make(200, 200, 200));
    var nodeGeometry = knight2.geometry;
    var shape = SCNPhysicsShape(geometry: nodeGeometry!, options: [SCNPhysicsShapeScaleKey:nodeScale])
    knight2.physicsBody = SCNPhysicsBody(type:SCNPhysicsBodyType.Static, shape: shape)            
    knight2.physicsBody?.categoryBitMask = rockCategory

    knight2.physicsBody?.angularVelocityFactor = SCNVector3Make(0.0,0.0,0.0)
    knight2.physicsBody?.collisionBitMask = 3
    knight2.name = "Student"          
    knight2.physicsBody?.mass = 1000
    scene?.rootNode.addChildNode(knight2)
}

Solution

  • SceneKit physics bodies model solid shapes. If you're trying to model an open space enclosed by boundaries — like a room or hallway — a single physics body won't help you. That'd fill in the volume of the room with an impassible area, and other physics bodies (with overlapping collision masks) would be forced out of that area.

    If you want to make an open space enclosed by boundaries, you need to create physics bodies for the boundaries. The SceneKitVehicle sample code illustrates doing this, creating separate physics bodies for the floor and walls of a room using SCNFloor and SCNBox geometries for each.