Physics Puzzles Reference — Soft8Soft
Description: Using puzzles to simulate physics behavior.

# Physics

These puzzles are used to simulate physics behavior of the objects.

For usage example, check out the Physics demo (source files available in the Asset Store).

## Contents

- Physics Puzzles Reference
  - create physics world
  - create rigid body
  - create soft body
  - remove physics body
  - apply body param
  - get body param
  - set body state
  - on simulation tick
  - snap body
  - add constraint to
  - remove constraint from
  - anchor soft body
  - apply soft body param
  - get soft body param
  - detect collisions and collision info
- Extending with JavaScript

#

## Physics Puzzles Reference

#

### create physics world

Initializes the physics engine using the specified gravity and frames-per-second parameters. The default gravity value of 9.8 corresponds to Earth surface conditions. Zero value means no gravity as in space. The higher fps value the better simulation quality at the expense of performance.

The soft body checker activates the soft body simulation capability.

Under the hood, this puzzle also enables collision detection and automatic synchronization with graphics.

#

### create rigid body

Creates a physics body from a specified object, of dynamic, kinematic, static, or ghost type. Assigns the collision shape and sets the mass for the body (valid for dynamic bodies only). Also works for a list of objects, a group (or a list of groups) or with the all objects puzzle.

Physics body types:

- dynamic — moved by the physics engine, influenced by collisions, and collide with other bodies.
- kinematic — moved by animation or user action. Dynamic objects will be pushed away but there is no influence from dynamics objects.
- static — cannot move but collide with other bodies.
- ghost — similar to kinematic but does not produce any collision response. Use it to detect collision between bodies (for example to implement proximity sensor).

Supported rigid body shapes:

- box — a box-shaped bounding.
- sphere — a sphere-shaped bounding.
- mesh — a mesh shape.
- capsule — a capsule shape stretched along up-down axis.
- cone — a cone shape stretched along up-down axis.
- cylinder — a cylinder shape stretched along up-down axis.
- empty — an empty shape. Usefull for creating constraint attachments and soft body anchor points.

For performance reasons, give priority to primitive physics shapes (boxes, spheres, capsules, cones and cylinders) over mesh shapes. Also, static meshes have much better performance than dynamic, kinematic, or ghost meshes.

#

### create soft body

Creates a soft body from a specified object with a given total mass and optional pressure params. Also works for a list of objects, a group (or a list of groups) or with the all objects puzzle.

Supported soft body shapes:

- volume — a closed pressurized 3D-dimentional volume.
- rope — a line object which behaves like a rope.
- patch — a polygonal surface like cloth or textile patch.

Don't forget to activate soft body simulation on the physics world before creating soft bodies.

#

### remove physics body

Removes physics from a specified object by destroying the physics body associated with it. Also works for a list of objects, a group (or a list of groups) or with the all objects puzzle.

#

### apply body param

Sets parameters for the physics body associated with a specified object. Also works for a list of objects, a group (or a list of groups) or with the all objects puzzle.

Parameters:

angular damping
  Coefficient of resistance that will slow down a rotating object: `0` — no damping, `1` — maximum damping. Input values are clamped to [0, 1] range.
angular factor
  Set rotational degrees of freedom for the specified body. For example, by setting Z component to zero you can disable whirling the body around up-down (Blender, Max) or front-back (Maya) axis.
angular velocity
  Set rotation speed vector.
ccd motion threshold
  Motion threshold used for simulating Continuous Collision Detection (CCD) physics. Specify low value, such as 0.001.
ccd swept sphere radius
  Radius of the swept sphere used for simulating Continuous Collision Detection (CCD) physics. This value should correspond to the size of the colliding objects. For example, to simulate a small bullet of size 0.01 m this value could be safely set to 0.5.
force
  Push a body in a specified direction by applying the specified force vector.
friction
  Coefficient of resistance of relative motion of solid bodies sliding against each other.
gravity
  Assign gravity individually for a specified body. This value can be specified as a vector or a number. In case of a number, the value sets up-down gravity factor (along Z axis for Blender/3ds Max or Y axis for Maya).
impulse
  Acts like Linear Velocity but also takes the body mass into account (heavier objects will acquire less speed).
linear damping
  Coefficient of resistance that will slow down a moving object: `0` - no damping (e.g. free fall), `1` - maximum damping (e.g. object falls with no acceleration). Input values are clamped to [0, 1] range.
linear factor
  Set positional degrees of freedom for the specified body. For example by setting Z component to zero you can disable up-down (Blender, Max) or front-back (Maya) movement of the body.
linear velocity
  Set movement speed vector.
margin
  Collision margin used to improve stability and performance of simulations. Specify margins only for mesh or cone collision shapes. For other collision shapes (box, sphere, capsule, cylinder) this value is calculated by the physics engine.
position
  Set body position (works like the snap body puzzle).
restitution
  Coefficient of elasticity: `0` — body is not elastic like clay, `1` — body behaves like being made from rubber.
rotation
  Set body rotation (euler rotation in XYZ order, works like the snap body puzzle).
stiffness
  Stiffness of soft bodies like volumes and ropes. Deprecated, use apply soft body param instead.
torque
  Spin a body in a specified direction.
torque impulse
  Acts like Angular Velocity but also takes the body mass into account (heavier objects will acquire less rotation speed).

When two bodies collide, friction and restitution parameters of both of them are taken into consideration.

#

### get body param

Gets a parameter from the physics body associated with a specified object.

Parameters:

angular damping
  Coefficient of resistance that will slow down a rotating object: `0` — no damping, `1` — maximum damping.
angular factor
  Rotational degrees of freedom for the specified body (XYZ).
angular velocity
  Rotation speed vector.
ccd motion threshold
  Motion threshold used for simulating Continuous Collision Detection (CCD) physics.
ccd swept sphere radius
  Radius of the swept sphere used for simulating Continuous Collision Detection (CCD) physics.
force
  Force vector applied to a body.
friction
  Coefficient of resistance of relative motion of solid bodies sliding against each other.
gravity
  Gravity vector applied to a body as XYZ value.
linear damping
  Coefficient of resistance that will slow down a moving object: `0` — no damping (e.g. free fall), `1` — maximum damping (e.g. object falls with no acceleration).
linear factor
  Positional degrees of freedom for the specified body (XYZ).
linear velocity
  Movement speed vector.
margin
  Collision margin used to improve stability and performance of simulations.
position
  Body XYZ position.
restitution
  Coefficient of elasticity: `0` — body is not elastic like clay, `1` — body behaves like being made from rubber.
rotation
  Body XYZ euler rotation.
stiffness
  Stiffness of soft bodies like volumes and ropes. Deprecated, use get soft body param instead.
torque
  Torque vector applied to the body.

#

### set body state

Change the state to the physics body associated with a specified object. Also works for a list of objects, a group (or a list of groups) or with the all objects puzzle.

Parameters:

- activate - activate sleeping physics body.
- sleep - force sleeping state for the body.
- enable simulation - enable body simulation (enabled by default).
- disable simulation - disable body simulation.
- reset - clear all forces and velocities applied to the physics body.
- enable contact response - allow body to collide with other bodies (enabled by default).
- disable contact response - disable body colliding.
- make dynamic - make body dynamic.
- make kinematic - make body kinematic.
- make static - make body static.
- enable deactivation - allow body to turn into sleeping state after a period of inactivity (enabled by default).
- disable deactivation - disable body sleeping.

#

### on simulation tick

Trigger puzzles specified in the do slot just before or just after the physics simulation tick.

Physics simulation tick corresponds to the FPS value specified when creating physics world and does not coincide with rendering frame. As such, we recommend that you apply forces/velocities/impulses before simulation tick and detect collisions between your bodies after simulation tick. This way you can achieve more stable and realistic simulations.

#

### snap body

Moves a physics body associated with a specified object, and the object itself, to the position of another object by copying its transform data. Also copies rotation. Does not work with lists, groups or the all objects puzzle.

Works similar to apply body param / position puzzle.

#

### add constraint to

Connect two physics bodies by a constraint of the given type.

Constraint types:

- hinge - connect the bodies by the shared axis.
- ball - connect the bodies by the ball-shaped socket.
- slider - limit movement of the bodies by the direction along the X axis.
- spring - connect two bodies by the spring-like joint.
- fixed - connect two bodies tightly.

#

### remove constraint from

Remove physics constraint.

#

### anchor soft body

Anchor soft body to a given rigid body at the point in space represented by the given vector.

#

### apply soft body param

Sets parameters for the soft body associated with a specified object. Also works for a list of objects, a group (or a list of groups) or with the all objects puzzle.

Parameters:

anchor hardness
  Coefficient of anchor hardness: `0` — no anchor influence, `1` — maximum anchor influence.
angular stiffness
  Angular stiffness: `0` — no angular stiffness, `1` — maximum angular stiffness.
collision flags
  Soft body collision flags: `0` — no collision with other rigid bodies, `1` — simplified collision, 17 — improved collision. Default value is 17.
damping coefficient
  Damping coefficient: `0` — no damping, `1` — maximum damping.
drag coefficient
  Drag force coefficient (aka fluid resistance). Must be a positive number.
dynamic friction
  Dynamic friction coefficient. `0` — no friction, `1.0` — maximum friction.
lift coefficient
  Lift force coefficient. Must be a positive number.
linear stiffness
  Linear stiffness: `0` — no linear stiffness, `1` — maximum linear stiffness.
position iterations
  Number of positions solver iterations. Higher values give more quality. Must be a positive integer.
pressure coefficient
  Pressure coefficient (e.g for balloons).
velocity iterations
  Number of velocity solver iterations. Higher values give move quality. Must be a positive integer.
wind velocity
  Wind velocity vector.

#

### get soft body param

Gets a parameter from the soft body associated with a specified object.

Parameters:

anchor hardness
  Coefficient of anchor hardness: `0` — no anchor influence, `1` — maximum anchor influence.
angular stiffness
  Angular stiffness: `0` — no angular stiffness, `1` — maximum angular stiffness.
collision flags
  Soft body collision flags: `0` — no collision with other rigid bodies, `1` — simplified collision, 17 — improved collision.
damping coefficient
  Damping coefficient: `0` — no damping, `1` — maximum damping.
drag coefficient
  Drag force coefficient (aka fluid resistance). Must be a positive number.
dynamic friction
  Dynamic friction coefficient. `0` — no friction, `1.0` — maximum friction.
lift coefficient
  Lift force coefficient.
linear stiffness
  Linear stiffness: `0` — no linear stiffness, `1` — maximum linear stiffness.
position iterations
  Number of positions solver iterations.
pressure coefficient
  Pressure coefficient (e.g for balloons).
velocity iterations
  Number of velocity solver iterations.
wind velocity
  Wind velocity vector.

#

### detect collisions and collision info

Detects if there is a collision at the moment of a specified body with another body (or any body from a list or a group). If there is a collision, the puzzles in the if touching do slot are triggered, otherwise - in the if not touching do.

The "detect collisions" puzzle triggers either of its callback slots every rendering frame.

The collision info puzzle outputs a dictionary with the following fields:

- objectA - the name of the first colliding body.
- objectB - the name of the second colliding body.
- distance - distance between points of collisions.
- positionOnA - XYZ coordinates of the collision point on the first object.
- positionOnB - XYZ coordinates of the collision point on the second object.
- normalOnB - XYZ components of the normal vector at the collision point on the second object.

#

## Extending with JavaScript

Before you start reading, please get familiar with the Using JavaScript section of this User Manual.

To build physics puzzles we use a JavaScript library called Ammo.js. This library is basically the popular Bullet physics engine compiled to be used in the browser.

To get familiar with Bullet, check out the Bullet Physics SDK Manual available on GitHub as well as official Bullet API Reference.

In Verge3D you can execute Bullet/Ammo.js APIs directly by using the Ammo namespace:

`const myVector = new Ammo.btVector3(1.0, 0.0, 0.0); console.log('My physics vector is:', myVector.x(), myVector.y(), myVector.z());`

Also you can get access to the following data structures we use in Puzzles via the `puzzles` argument of the `runCode()` function of your_app_name.js module or the built-in `puzzles` variable inside the exec script puzzle:

### World

Depending on the initialized physics world it can be an instance to btDiscreteDynamicsWorld or btSoftRigidDynamicsWorld class:

`const gravity = puzzles.physics.world.getGravity(); console.log('World gravity:', gravity.y());`

### Physics Bodies

Physics bodies are stored as key-value data inside the puzzles.physics.bodies object:

`const body = puzzles.physics.bodies['Whirligig']; console.log('Body mass:', 1.0 / body.getInvMass());`

Rigid bodies are instances of the btRigidBody class, while soft bodies are instances of the btSoftBody class.

### Physics Constraints

Bullet/Ammo constraints are stored as key-value data inside the two-dimensional puzzles.physics.constraints object:

`const hingeConstraint = puzzles.physics.constraints['Suzanne']['Axis']; hingeConstraint.enableAngularMotor(true, 10, 10);`

The names represent the constraint's first and second bodies respectively.

### Physics Sync List

Verge3D puzzles use the so-called synchronization list to move objects represented by physics bodies in space. Sync list is not directly accessible, so you need to use the following API methods to add/remove your bodies to/from that list.

`// add obj / body to the sync list // the type can be 'DYNAMIC', 'KINEMATIC', 'STATIC', 'GHOST', or 'SOFT_BODY' puzzles.physics.addToSyncList(obj, body, 'DYNAMIC'); // remove obj / body from the sync list puzzles.physics.removeFromSyncList(obj, body);`

## Having Troubles with Puzzles?

Seek help on the forums!