# Physics: Gravity, Collisions, Forces

The jMonkeyEngine3 has built-in support for
via the `com.jme3.bullet` package.

Game Physics are used in applications that simulate mass/gravity, collisions, and friction. Think of pool billiard or car racing simulations.

If you are looking for info on how to respond to physics events, read about Physics Listeners.

## Technical Overview

Bullet physics runs internally at 60fps by default. This rate is not dependent on the actual framerate and it does not lock the framerate at 60fps. Instead, when the actual fps is higher than the physics framerate the system will display interpolated positions for the physics entities. When the framerate is lower than the physics framerate the physics space will be stepped multiple times per frame to make up for the missing calculations.

A bullet physics space can be created with a BulletAppState. The updating and syncing of the actual physics entities happens in the following way:

A "normal" update loop with physics looks like this:

1. collision callbacks (BulletAppState.update())
2. user update (simpleUpdate / update)
3. physics to scenegraph syncing/applying (updateLogicalState())
4. stepping physics (before / in parallel to Application.render())

When you use physics, 1 unit (1.0f) equals 1 meter, weight is expressed in kilograms, most torque and rotation values are expressed in radians.

## Sample Code

Full code samples are here:

## Physics Application

A short overview of how to write a jME application with Physics capabilities:

Do the following once per application to gain access to the `physicsSpace` object:

1. Make you application extend `com.jme3.app.SimpleApplication`.
2. Create a BulletAppState field:

       private BulletAppState bulletAppState;

3. Initialize your bulletAppState and attach it to the state manager:

       public void simpleInitApp() {
           bulletAppState = new BulletAppState();
           stateManager.attach(bulletAppState);
           ...

You can also access the BulletAppState via the state manager:

    stateManager.getState(BulletAppState.class)

For each Spatial that you want to be physical:

1. Create a CollisionShape.
2. Create a PhysicsControl by supplying the CollisionShape and mass.
   - E.g. `com.jme3.bullet.control.RigidBodyControl`
3. Add the PhysicsControl to the Spatial.
4. Add the PhysicsControl to the physicsSpace object.
5. Attach the Spatial to the rootNode, as usual.
6. (Optional) Implement the `PhysicsCollisionListener` interface to respond to `PhysicsCollisionEvent`s if desired.

### Collision Shapes

A Collision Shape is a simplified shape for which physics are easier to calculate than for the true shape of the model. This simplication approach speeds up the simulation greatly.

Before you can create a Physics Control, you must create a Collision Shape from the `com.jme3.bullet.collision.shapes` package. (Read the tip under "PhysicsControls Code Samples" to learn how to use default CollisionShapes for Boxes and Spheres.)

Shape | Usage | Examples
--- | --- | ---
BoxCollisionShape | Box shaped entities Does not roll. | Bricks, crates, simple oblong entities.
SphereCollisionShape | Spherical entities. Can roll. | Balls, simple compact entities.
CylinderCollisionShape | Tube-shaped and disc-shaped entities. Can roll on one side. | Pillars, wheels.
CapsuleCollisionShape | A compound of a cylinder plus two spheres at the top and bottom. Is locked to stay upright, does not roll. | Optimized for CharacterControls: A cylinder-shaped body does not get stuck at corners and vertical obstacles; the rounded top and bottom do not get stuck on stair steps and ground obstacles.
CompoundCollisionShape | A CompoundCollisionShape allows custom combinations of box/sphere/cylinder shapes to form another more complex shape. | Complex shapes.
MeshCollisionShape | A free-form mesh-accurate shape that wraps itself around a static entity. Limitations: Only non-mesh collision shapes (sphere, box, cylinder, compound) can collide with mesh-accurate collision shapes. Only works for static obstacles. | A whole static game level model.
GImpactCollisionShape | This free-form Mesh Collision Shape that wraps itself around dynamically moving entities. Uses . Limitations: CPU intensive, use sparingly! We recommend using HullCollisionShapes or CompoundShapes made of simple shapes if you need improved performance. | Physics simulation of a complex object.
HeightFieldCollisionShape | Optimized Mesh Collision Shape for static terrains. This shape is much faster than a other Free-Form Mesh Shapes. Requires heightmap data. | Optimized for terrains.
HullCollisionShape | A collision shape that is based on a mesh but is a simplified convex version. | …
SimplexCollisionShape | A physical point, line, triangle, or quad Collision Shape, defined by one to four points. | Guardrails
PlaneCollisionShape | A 2D plane | Flat solid floor or wall.

Pick the right shape for the mesh for what you want to do: If you give a box a sphere collision shape, it will roll; if you give a ball a box collision shape, it will sit on a slope. Make collision shapes visible by adding the following line after the bulletAppState initialization:
`bulletAppState.getPhysicsSpace().enableDebug(assetManager);`

Let's look at examples of how to use the CollisionShape constructor:

### CollisionShape Code Samples

MeshCompoundShape and MeshCollisionShape are both mesh-accurate and are intended for immobile scene entities, such as terrains, buildings, or whole shooter levels. Limitation: Only collisions of non-mesh-accurate shapes (sphere, box, etc) shapes can be detected against mesh-accurate shapes.

    CompoundCollisionShape myComplexShape =
        CollisionShapeFactory.createMeshShape((Node) myComplexGeometry );

An angular, non-mesh-accurate compound shape:

    CompoundCollisionShape boxShape =
        CollisionShapeFactory.createBoxCompoundShape((Node) someBox);

SphereCollisionShape, BoxCollisionShape, CapsuleCollisionShape are also not mesh-accurate, but have better performance. The can be added to anything, and collisions between them and any other shape can be detected.

    SphereCollisionShape sphereShape =
        new SphereCollisionShape(1.0f);

## PhysicsControls

BulletPhysics are available in jME3 through Bullet Physics Controls from the com.jme3.bullet.control package. PhysicsControls are the recommended way to use physics in a jME3 application. PhysicsControls are flexible and can be added to any Spatial to make it act according to physical properties. jME's PhysicsControl classes directly extend Bullet Physics objects.

Physics Control | Purpose
--- | ---
RigidBodyControl | Use for dynamic physical entities in the scene – things that are freely affected by physical forces such as collisions, forces, or changing gravity. For example: Impacting projectiles, moving obstacles like crates, rolling and bouncing balls, space ships…
CharacterControl | Use for upright characters (persons, animals) that moves and stands orthogonally to the X/Z plane. It is not affected by directional forces or gravity and it does not fall over (as a RigidBodyControl'ed spatial would), a CharacterControl's spatial is permanently locked locked upright (as a walking character would).
GhostControl | Use for collision and intersection detection between physical entities. A GhostControl is non-solid and invisible, and it moves with the Spatial it is attached to. Use this for interactive game elements that do not have a visible solid Geometry: A monster's "aggro radius", motion detectors, photoelectric alarm sensors, poisonous or radioactive perimeters, life-draining ghosts, etc.
VehicleControl PhysicsVehicleWheel | Use for vehicles such as cars, tanks, hover crafts, ships, motorcycles.
RagDollControl | Use for collapsing, flailing, or loosely falling characters or with a Ragdoll (or puppet-on-strings) behaviour.

### PhysicsControls Code Samples

The various Physics Control constructors expect a Collision Shape (here thingShape) and a mass (a float).

    RigidBodyControl myControl=new RigidBodyControl( thingShape , 1.0f );

To make the Physics Control visible in the scene, you must attach the Control to a Geometry (e.g. a model named myGeometry):

    myGeometry.addControl(myControl);

This code sample creates a physical Character:

    // Load any model
    Node model = (Node) assetManager.loadModel("Models/myCharacterModel.mesh.xml");
    rootNode.attachChild(model);
    // Create a appropriate physical shape for it
    CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(1.5f, 6f, 1);
    CharacterControl character_phys = new CharacterControl(capsuleShape, 0.01f);
    // Attach physical properties to model and PhysicsSpace
    model.addControl(character_phys);
    bulletAppState.getPhysicsSpace().add(character_phys);

Spheres and Boxes can fall back to the correct default CollisionShape if you do not specify a CollisionShape in the RigidBodyControl constructor.

For example, the following creates a box with the correct Box Collision Shape:

    Box(1,1,1);
    myBox.addControl(new RigidBodyControl( 1.0f )); // implicit BoxCollisionShape
    bulletAppState.getPhysicsSpace().add(myBox);

## Physics Space

The Physics Space is an object in BulletAppState that is like a rootNode for Physics Controls. It manages global settings.

1. You can specify parameters such as gravity and accuracy.

       bulletAppState.getPhysicsSpace().setGravity(new Vector3f(0f,-1f,0f));
       bulletAppState.getPhysicsSpace().setAccuracy(0.005f);

2. Add all PhysicsControls to the PhysicsSpace.

       bulletAppState.getPhysicsSpace().add(myPhysicsControl); ...

3. Add each PhysicsControl to a Spatial.

       myModel.addControl(myPhysicsControl); ...

4. Attach the Spatial to the rootNode, as always.

       rootNode.attachChild(myModel); ...

You remove physical entities from the scene by removing their PhysicsControl from the PhysicsSpace and also their Spatial from the rootNode:

    bulletAppState.getPhysicsSpace().remove(myPhysicsControl);
    myModel.removeFromParent();

## Properties of Physical Entities

On a PhysicsControl, you can set the following physical properties.

RigidBodyControl Method | Property
--- | ---

setGravity(new Vector3f(0f,-10f,0f))

You can change the gravity of individual physics entities after they were added to the physics space. Gravity is a vector pointing towards the center of gravity. The longer the vector, the stronger is gravity. If gravity is the same absolute direction for all entities, set this vector globally on the physics space. If the center of gravity is relative (e.g. towards a planet's core or towards a black hole) then you have to use this method to adjust the vectors of all entities at each tick of the update loop.

setFriction(1f) | Friction. Ice and slides have low friction, the are slippery. Soil, concrete and rock have high friction.
setMass(1f) | Sets the mass. Dynamic entities have masses > 0.0f. Heavy dynamic entities need more force to be moved and light ones move with small amounts of force. Static immobile entities (obstacles, including buildings and terrains) must have mass = 0.0f.
setPhysicsLocation() | Positions the entity. Do not use setLocalTranslation() for physical entities.. Important: Make certain not to make CollisionShapes overlap when positioning them (Use the debug mode to check the shapes).
setPhysicsRotation() | Rotates the entity. Do not use setLocalRotate() for physical entities.
setRestitution(0.0f) | How bouncy an entity is, normally 0.0f. For a bouncy, such as rubber balls, set this > 0.0f. This setting has an impact on performance, so use it sparingly.

setKinematic(true)

A kinematic RigidBodyControl'ed entity is not affected by gravity or other forces! You write translation and rotation code in the update loop to describe the motion of physical entities. A kinematic has a mass and is solid (e.g. characters can stand on it), this means a kinematic affects other physics entities that bump into it (e.g. pushes them away). You also can attach joints and hinges to it ("air hook"). The position of a kinematic RigidBodyControl is updated depending on its spatial's translation.
By default, PhysicsControls are not kinematic.

setCcdMotionThreshold(0.1f) | The amount of motion in 1 physics tick to trigger the continuous motion detection. Rarely used, but necessary if you need to fiddle with details.

CharacterControl Method | Property
--- | ---
setUpAxis(1) | CharacterControls have a fixed upward axis! This means they cannot fall over. Values: 0 = X axis , 1 = Y axis , 2 = Z axis. Default: 1, because for characters and vehicle, up is typically along the Y axis.
setJumpSpeed(1f) | Jump speed (movement along up axis)
setFallSpeed(1f) | Fall speed (movement along negative up axis)
setMaxSlope(1.5f) | How steep the slopes and steps are that the character can climb without considering them an obstacle. Higher obstacles need to be jumped. In world units.
setGravity(1f) | The intensity of gravity for this CharacterControl'ed entity. To change the direction of gravity for a character, modify the up axis.

### Kinematic vs Dynamic vs Static

All physical entities…

- must not overlap.
- can detect collisions and report several values about the impact.
- can respond dynamically, or statically, or kinematically to collisions.

Property | Static | Kinematic | Dynamic
Examples | Immobile obstacles: Floors, walls, buildings, … | Remote-controlled entities: Airships, meteorites, doors; networked or remote-controlled NPCs; invisible "airhooks" for hinges and joints. | Interactive entities: Rolling balls, movable crates, falling pillar, space ship…
Does it have a mass? | no, 0.0f | yes1), >0.0f | yes, >0.0f
How does it move? | never | setLocalTranslation(); | setLinearVelocity(); applyForce(); setWalkDirection(); for CharacterControl
How to place in scene? | setPhysicsLocation(); setPhysicsRotation() | setLocalTranslation(); setLocalRotation(); | setPhysicsLocation(); setPhysicsRotation()
Can it move and push others? | no | yes | yes
Is is affected by forces? (Falls when it mid-air? Can be pushed by others?) | no | no | yes
How to activate? | setMass(0f); setKinematic(false); | setMass(1f); setKinematic(true); | setMass(1f); setKinematic(false);

You move Spatials with a kinematic RigidBodyControl programmatically, that is by using setLocalTranslation() or move() in the update() loop, or using a MotionPath. You can also "hang them up in mid-air" and attach other PhysicsControls to them using hinges and joints.

## Forces: Moving Physical Entities

Use the following methods to move physics entities.

PhysicsControl Method | Motion
--- | ---
setLinearVelocity(new Vector3f(0f,0f,1f)) | Set the linear speed of this entity.
setAngularVelocity(new Vector3f(0f,0f,1f)) | Set the rotational speed of the entity; the x, y and z component are the speed of rotation around that axis.
applyCentralForce(…) | Move (push) the entity once with a certain moment, expressed as a Vector3f.
applyForce(…) | Move (push) the entity once with a certain moment, expressed as a Vector3f. Optionally, you can specify where on the entity the pushing force hits.
applyTorque(…) | Rotate (twist) the entity once around its axes, expressed as a Vector3f.
applyImpulse(…) | An idealised change of momentum. This is the kind of push that you would use on a pool billiard ball.
applyTorqueImpulse(…) | An idealised change of momentum. This is the kind of push that you would use on a pool billiard ball.
setWalkDirection(new Vector3f(0f,0f,0.1f)) | (CharacterControl only) Make a physical character walk. CharacterControls are locked upright to prevent falling over. Use `setWalkDirection(Vector3f.ZERO)` to stop a directional motion.
clearForces() | Cancels out all forces (force, torque) etc and stops the motion.

It is technically possible to position PhysicsControls using setLocalTranslation(), e.g. to place them in their start position in the scene. However you must be very careful not to cause an "impossible state" where one physical entity overlaps with another! Within the game, you typically use the setters shown here exclusively.

PhysicsControls also supports the following features:

PhysicsControl Method | Property
--- | ---
setCollisionShape(collisionShape) | Changes the collision shape.
setCollideWithGroups() setCollisionGroup() addCollideWithGroup(COLLISION_GROUP_01) removeCollideWithGroup(COLLISION_GROUP_01) | Collision Groups are integer bit masks – enums are available in CollisionObject. All physics entities are by default in COLLISION_GROUP_01. Two entities collide when the collideWithGroups set of one contains, the Collision Group of the other.
setDamping(float, float) | The first value is the linear threshold and the second the angular.
setAngularFactor(1f) | Set the amount of rotation that will be applied. A value of zero will cancel all rotational force outcome.
setCcdSweptSphereRadius() | ?
setSleepingThreshold(float,float) | Sets the sleeping thresholds which define when the entity gets deactivated to save resources. Low values keep the entity active when it barely moves. The first value is the linear threshold and the second the angular.

## Best Practices

- You can control the game by triggering forces; or may want to respond to collisions, e.g. by substracting health points, or by playing a sound. To specify how the game responds to physics events, you use Physics Listeners.

- Do not overuse PhysicsControls. Although PhysicsControls are put to “sleep” when they are not moving, creating a world solely out of dynamic physics nodes will quickly bring you to the limits of your computer's capabilities.

- You can use normal non-physical Spatials in the same scene next to physical ones. Use the non-physical ones for non-solid things for which you do not want to detect collisions (ghost, foliage, plants, effects, …). This improves performance.

- If you get weird behaviour, such as physical nodes jittering wildy and being ejected "for no apparent reason", it usually means you have created an impossible state. Verify that none of the collision shapes overlap. This can happen when you create physical nodes in positions that are too close to other nodes; or if you position a physical node using setLocalTranslation() and it touches another node's collision shape.

- For large static meshes like shooter levels or terrain it is best to divide the scene model into multiple physics entities, with each its own CollisionShape. A huge city level should not be one huge mesh (model) of pavement and streets and buildings. Instead, you make individual models for buildings, for pieces of pavement, for pieces of streets, etc. Position them next to one another to form the whole city, and give each piece its own optimal CollisionShape. E.g. streets can use a fast PlaneCollisionShape if you keep them separate for buildings. Breaking the level into manageable pieces helps the engine improve performance: The less CPU-intensive
  can now filter out parts of the scene that are behind you or out of reach, and it only calculates the details of collisions for parts that are actually close to the action.

physics, documentation, control
1) Inertia is calculated for kinematic entities, and you need mass to do that.

view online version