Game World
This section contains the references for building and querying the world a game takes place in: maps of areas, pathfinding, and physics.
- coordinate_map stores a world as boxes of tiles, such as rooms, floors, walls and zones, and quickly finds the ones at any position. This suits the grid based worlds of most audio games.
- pathfinder finds the cheapest way between two tiles, asking the game how difficult each tile is to cross, which lets characters walk around obstacles.
- physics_world simulates bodies of many shapes with JoltPhysics, for worlds where things fall, collide and are pushed around, and physics_character moves a player through such a world. The physics world can also be traced with rays, such as to find what the player is facing, and given to the nvgt_phonon plugin's sound_environment so sound is occluded and reflected by it.
The two approaches can be combined, such as using a coordinate_map for what the player is standing on and a physics_world for objects that move.
Classes
coordinate_map
A map of rectangular areas in a 3D grid, which can be looked up quickly by position, such as the rooms, floors, walls and zones of a game's world.
coordinate_map();
Remarks:
Audio games often describe their worlds as boxes: a room of carpet from 0 to 20 on x and y, a wall at x 21, a pool of water in one corner, a zone where a certain music plays. A coordinate_map stores such boxes as coordinate_map_area objects, each with a priority, optional rotation, flags and data of your choosing, and finds the ones at any position without checking every area, as they are divided into frames of the grid.
Coordinates are whole tiles, so an area from minx 0 to maxx 9 covers the 10 tiles 0 through 9, as well as any position from 0.0 up to but not including 10.0. Where areas overlap, the one with the highest priority usually wins, such as a rug placed over a floor, and get_area() returns it.
An area stays in the map until it is unframed with coordinate_map_area::unframe() or the map is reset, even if the script no longer holds a handle to it.
Example:
void main() {
coordinate_map map;
map.add_area(0, 20, 0, 20, 0, 0, 0, null, "carpet", "", "", 0);
map.add_area(5, 8, 5, 8, 0, 0, 0, null, "water", "", "", 1); // A pool in the room, with a higher priority so it wins over the carpet.
map.add_area(21, 21, 0, 20, 0, 10, 0, null, "wall", "", "", 2, 1); // A wall, with flag 1 marking it as solid.
coordinate_map_area@ a = map.get_area(6, 6, 0);
string info = "At 6, 6 you are on " + a.data1;
@a = map.get_area(2, 3, 0);
info += "\nAt 2, 3 you are on " + a.data1;
coordinate_map_area@[]@ areas = map.get_areas(6, 6, 0);
info += "\n" + areas.length() + " areas overlap 6, 6";
info += "\nSolid areas within 2 tiles of 20, 10: " + map.get_areas(20, 10, 0, 2, null, 1).length();
alert("Map", info);
}
Methods
add_area
Add an area to the map.
coordinate_map_area@ coordinate_map::add_area(float minx, float maxx, float miny, float maxy, float minz, float maxz, float rotation, any@ primary_data, const string&in data1, const string&in data2, const string&in data3, int priority, int64 flags = 0);
Arguments:
- float minx: the lowest x tile of the area.
- float maxx: the highest x tile of the area, which is included in it.
- float miny: the lowest y tile of the area.
- float maxy: the highest y tile of the area.
- float minz: the lowest z tile of the area.
- float maxz: the highest z tile of the area.
- float rotation: how far the area is rotated around its center on the x y plane, in radians, or 0 for none.
- any@ primary_data: any value or handle to store with the area, such as the object it represents, or null.
- const string&in data1: a string to store with the area, such as the name of its surface or sound.
- const string&in data2: another string to store with the area.
- const string&in data3: another string to store with the area.
- int priority: the priority of the area. Where areas overlap, get_area() returns the one with the highest priority.
- int64 flags = 0: bits of your choosing that searches can require or exclude, such as one bit for solid areas and another for water.
Returns:
coordinate_map_area@: the new area, which is already in the map.
Remarks:
The data and flags can be anything a game needs. A common pattern is to store the type of the area, such as a surface or a wall, in data1, and a handle to a script object with more information in primary_data.
get_area
Get the area with the highest priority at a position.
coordinate_map_area@ coordinate_map::get_area(float x, float y, float z, int priority = -1, float d = 0.0, coordinate_map_filter_callback@ filter_callback = null, int64 required_flags = 0, int64 excluded_flags = 0) const;
Arguments:
- float x: the x coordinate of the position.
- float y: the y coordinate of the position.
- float z: the z coordinate of the position.
- int priority = -1: if 0 or more, only areas with a priority lower than this are considered, which finds what is under the top area. -1 considers every area.
- float d = 0.0: how far around the position to search.
- coordinate_map_filter_callback@ filter_callback = null: a function called for each area found, returning true to include it or false to skip it, or null to include every area.
- int64 required_flags = 0: only include areas whose flags have all of these bits set.
- int64 excluded_flags = 0: skip areas whose flags have any of these bits set.
Returns:
coordinate_map_area@: the area, or null if there is none at the position.
Remarks:
This is the usual way to find out what the player is standing on or in.
get_areas
Get every area at a position, or within a box.
array<coordinate_map_area@>@ coordinate_map::get_areas(float x, float y, float z, float d = 0.0, coordinate_map_filter_callback@ filter_callback = null, int64 required_flags = 0, int64 excluded_flags = 0) const;array<coordinate_map_area@>@ coordinate_map::get_areas(float minx, float maxx, float miny, float maxy, float minz, float maxz, float d = 0.0, coordinate_map_filter_callback@ filter_callback = null, int64 required_flags = 0, int64 excluded_flags = 0) const;
Arguments:
- float x (1): the x coordinate of the position.
- float y (1): the y coordinate of the position.
- float z (1): the z coordinate of the position.
- float d = 0.0: how far around the position or box to search, which finds areas within this distance of it.
- coordinate_map_filter_callback@ filter_callback = null: a function called for each area found, returning true to include it or false to skip it, or null to include every area.
- int64 required_flags = 0: only include areas whose flags have all of these bits set.
- int64 excluded_flags = 0: skip areas whose flags have any of these bits set.
- float minx (2): the lowest x of the box to search.
- float maxx (2): the highest x of the box to search.
- float miny (2): the lowest y of the box to search.
- float maxy (2): the highest y of the box to search.
- float minz (2): the lowest z of the box to search.
- float maxz (2): the highest z of the box to search.
Returns:
array<coordinate_map_area@>@: the areas found. For a position they are sorted by priority, lowest first. For a box, only areas lying entirely within it, expanded by d, are returned.
Remarks:
Searching with a distance is useful for finding what is near the player, such as walls to warn them about or objects they could pick up.
reset
Remove every area from the map.
void coordinate_map::reset();
Remarks:
Areas that the script still holds handles to continue to exist, but are no longer in the map, and can be put back with coordinate_map_area::reframe().
coordinate_map_area
An area of a coordinate_map, a box of tiles with a priority, flags and data.
Remarks:
Areas can't be created directly, they are created by coordinate_map::add_area(). Their bounds can only be changed with set(), set_area() and set_rotation(), which move them within the map.
Methods
is_in_area
Find out whether a position is in the area.
bool coordinate_map_area::is_in_area(float x, float y, float z, float d = 0.0, coordinate_map_filter_callback@ filter_callback = null, int64 required_flags = 0, int64 excluded_flags = 0) const;
Arguments:
- float x: the x coordinate of the position.
- float y: the y coordinate of the position.
- float z: the z coordinate of the position.
- float d = 0.0: how far outside the area the position may be and still count.
- coordinate_map_filter_callback@ filter_callback = null: a function called for each area found, returning true to include it or false to skip it, or null to include every area.
- int64 required_flags = 0: only include areas whose flags have all of these bits set.
- int64 excluded_flags = 0: skip areas whose flags have any of these bits set.
Returns:
bool: true if the position is in the area, taking its rotation into account, and the area passes the filters, false otherwise.
reframe
Put an area that was removed with unframe() back into its map.
void coordinate_map_area::reframe();
set
Change the bounds and rotation of the area, moving it within the map.
void coordinate_map_area::set(float minx, float maxx, float miny, float maxy, float minz, float maxz, float theta);
Arguments:
- float minx: the lowest x tile.
- float maxx: the highest x tile.
- float miny: the lowest y tile.
- float maxy: the highest y tile.
- float minz: the lowest z tile.
- float maxz: the highest z tile.
- float theta: the rotation around the area's center in radians.
Remarks:
This is how doors that open and platforms that move are made.
set_area
Change the bounds of the area, keeping its rotation.
void coordinate_map_area::set_area(float minx, float maxx, float miny, float maxy, float minz, float maxz);
Arguments:
- float minx: the lowest x tile.
- float maxx: the highest x tile.
- float miny: the lowest y tile.
- float maxy: the highest y tile.
- float minz: the lowest z tile.
- float maxz: the highest z tile.
set_rotation
Change the rotation of the area, keeping its bounds.
void coordinate_map_area::set_rotation(float theta);
Arguments:
- float theta: the rotation around the area's center in radians.
unframe
Remove the area from its map, so searches no longer find it.
void coordinate_map_area::unframe();
Remarks:
This is how an area is deleted from a map. The area is destroyed once the script no longer holds a handle to it, or can be put back with reframe().
Properties
data1
The first string stored with the area.
const string coordinate_map_area::data1;
data2
The second string stored with the area.
const string coordinate_map_area::data2;
data3
The third string stored with the area.
const string coordinate_map_area::data3;
flags
Bits of your choosing that searches can require or exclude.
int64 coordinate_map_area::flags;
Remarks:
Unlike the other properties, this can be changed directly.
framed
Whether the area is in its map, which it isn't after unframe() or coordinate_map::reset().
const bool coordinate_map_area::framed;
map
The map the area belongs to, or null if the map has been destroyed.
const coordinate_map@ coordinate_map_area::map;
maxx
The highest x tile of the area, which is included in it.
const float coordinate_map_area::maxx;
maxy
The highest y tile of the area.
const float coordinate_map_area::maxy;
maxz
The highest z tile of the area.
const float coordinate_map_area::maxz;
minx
The lowest x tile of the area.
const float coordinate_map_area::minx;
miny
The lowest y tile of the area.
const float coordinate_map_area::miny;
minz
The lowest z tile of the area.
const float coordinate_map_area::minz;
primary_data
The value or handle stored with the area, or null.
any@ coordinate_map_area::primary_data;
Remarks:
Retrieve it as the type it was stored as, such as area.primary_data.retrieve(@obj).
priority
The priority of the area. Where areas overlap, the one with the highest priority is returned by coordinate_map::get_area().
const int coordinate_map_area::priority;
rotation
The rotation of the area around its center on the x y plane, in radians.
const float coordinate_map_area::rotation;
pathfinder
Find the cheapest path between two tiles of a grid, asking a callback how difficult each tile is to cross.
pathfinder(int size = 1024, bool cache = true);
Arguments:
int size = 1024: how many tiles the pathfinder allocates room for at a time, from 1 to 16777216. Larger values use more memory but search large maps with fewer allocations.
bool cache = true: whether to remember the paths and tile difficulties found, which makes finding paths again much faster until reset() is called. Callbacks that take the parent tile can't be used with caching.
Remarks:
Give the pathfinder a callback with set_callback_function(), which returns how difficult a tile is to cross: 0 for open ground, higher numbers up to 9 for harder terrain such as mud or stairs, and 10 or more for tiles that can't be crossed at all, such as walls. find() then returns the path from one tile to another that costs the least, moving between neighboring tiles in x, y and z.
The callback is called many times during a search, so it should be fast, such as looking up a coordinate_map. With caching, a tile's difficulty is only asked for once until reset(), so call reset(), or set automatic_reset, when the map changes.
The search uses the A* algorithm from the MicroPather library. Coordinates must be between -524288 and 524287.
Example:
coordinate_map map;
int tile_difficulty(int x, int y, int z, any@ data) {
coordinate_map_area@ a = map.get_area(x, y, z);
if (@a == null) return 10; // Outside the map.
if (a.data1 == "wall") return 10;
if (a.data1 == "mud") return 5;
return 0;
}
void main() {
map.add_area(0, 20, 0, 20, 0, 0, 0, null, "floor", "", "", 0);
map.add_area(10, 10, 0, 15, 0, 0, 0, null, "wall", "", "", 1); // A wall with a gap at the top.
map.add_area(3, 6, 3, 6, 0, 0, 0, null, "mud", "", "", 1);
pathfinder pf;
pf.allow_diagonals = true;
pf.set_callback_function(tile_difficulty);
vector[]@ path = pf.find(2, 2, 0, 18, 2, 0);
if (path.length() == 0) {
alert("Pathfinder", "There is no way there.");
return;
}
alert("Pathfinder", "The path takes " + path.length() + " steps, costing " + round(pf.total_cost, 2) + ", and passes " + path[path.length() / 2] + " halfway.");
}
Methods
cancel
Stop the search in progress, so that find() returns an empty path.
void pathfinder::cancel();
Remarks:
This is for calling from within the callback, such as when a search is taking too long.
find
Find the cheapest path between two tiles.
array<vector>@ pathfinder::find(int start_x, int start_y, int start_z, int end_x, int end_y, int end_z, any@ callback_data = null);array<vector>@ pathfinder::find(int start_x, int start_y, int end_x, int end_y, string user_data = "");
Arguments:
- int start_x: the x coordinate to start from.
- int start_y: the y coordinate to start from.
- int start_z (1): the z coordinate to start from.
- int end_x: the x coordinate to go to.
- int end_y: the y coordinate to go to.
- int end_z (1): the z coordinate to go to.
- any@ callback_data = null (1): a value or handle passed to every call of the callback, such as the map or character the path is for.
- string user_data = "" (2): a string passed to every call of a legacy callback.
Returns:
array
Remarks:
There is no path when the start or end can't be crossed, every route is blocked, the destination is beyond search_range, no callback has been set, or a search is already in progress. total_cost holds the cost of the path found.
The 2D overload, which takes no z coordinates and a string of user data, is for code ported from BGT and only works with a legacy callback.
reset
Forget the tile difficulties and paths cached by previous searches.
void pathfinder::reset();
Remarks:
Call this whenever the map changes, such as when a door opens. If called from within the callback, the reset happens once the search ends.
set_callback_function
Set the function that says how difficult each tile is to cross.
void pathfinder::set_callback_function(pathfinder_callback@ callback);void pathfinder::set_callback_function(pathfinder_callback_ex@ callback);void pathfinder::set_callback_function(pathfinder_callback_legacy@ callback);
Arguments:
- pathfinder_callback@ callback: the function, which returns 0 to 9 for a tile that can be crossed, with higher numbers being more difficult, or 10 or more for one that can't. It can take the coordinates of the tile and the callback_data given to find(), and also the tile the search is coming from, the parent, for terrain whose difficulty depends on the direction of travel.
Remarks:
Callbacks that take the parent tile, pathfinder_callback_ex and pathfinder_callback_legacy, can't be used with caching, and an exception is thrown if the pathfinder was created with cache set to true. The legacy callback is for code ported from BGT, used with the 2D find().
Properties
allow_diagonals
Whether paths can move diagonally between tiles.
bool pathfinder::allow_diagonals;
Remarks:
This defaults to false, so paths only move along the x, y and z axes.
automatic_reset
Whether the cache is reset before every search, for maps that change often.
bool pathfinder::automatic_reset;
Remarks:
This defaults to false.
desperation_factor
How much more willing the pathfinder is to cross difficult tiles, from 0 to 10.
int pathfinder::desperation_factor;
Remarks:
This is subtracted from the difficulty of every tile that can be crossed, so that with a desperation factor of 5 a tile of difficulty 5 costs no more than open ground. Tiles of difficulty 10 or more stay impassable. Raising it after a search fails lets a character take a harder route rather than none.
search_range
How far from the start a search may go on each axis, or 0 for no limit.
int pathfinder::search_range;
Remarks:
Limiting the range stops a search for an unreachable destination from exploring an entire large map. A destination further away than this has no path.
solving
Whether a search is in progress, which is only true while the callback is being called.
const bool pathfinder::solving;
total_cost
The cost of the last path found, or 0 if none was.
const float pathfinder::total_cost;
Remarks:
Each step costs its tile's difficulty plus 1, multiplied by about 1.41 for diagonal steps.
physics_body_id
A physics_body_id identifies a body in a physics_world. It is a small value that is cheap to copy and store, returned by physics_world::create_and_add_body() and accepted by the methods of the world that read or change bodies. Ids are only meaningful for the world that made them.
physics_body_id();physics_body_id(uint raw_id);physics_body_id(const physics_body_id&in other);
Arguments (2):
- uint raw_id: a value previously obtained from the
rawproperty.
Arguments (3):
- const physics_body_id&in other: the id to copy.
Remarks:
A default constructed id is invalid. Ids are compared with ==, and convert to a string so that they can be printed.
The index of an id identifies the slot a body occupies in the world, while its sequence number changes every time the slot is reused, so an id of a destroyed body does not accidentally refer to a new one.
You usually don't need to worry too much about the guts of this object, it is enough to know that it's what you use to identify bodies in a physics world.
Properties
index
The slot the body occupies in its world.
const uint physics_body_id::index;
is_invalid
True if this id does not refer to a body, for example because creating the body failed or the id was never set.
const bool physics_body_id::is_invalid;
raw
The index and sequence number combined into one number, which can be stored and passed to the physics_body_id(uint) constructor.
const uint physics_body_id::raw;
sequence_number
A number that changes each time the body's slot is reused, so that ids of old bodies can be told from the ones that replaced them.
const uint8 physics_body_id::sequence_number;
physics_box_shape
A box, whose sides are straight along the shape's axes. It is derived from physics_convex_shape and physics_shape and has all of their properties, as well as those listed here. Create one with physics_box_shape_create(), see physics_shape for an overview of the shapes.
Properties
convex_radius
How much the edges of the box are rounded.
const float physics_box_shape::convex_radius;
half_extent
Half of the size of the box along each axis.
const vector physics_box_shape::half_extent;
physics_capsule_shape
A cylinder with half spheres on the ends. It is derived from physics_convex_shape and physics_shape and has all of their properties, as well as those listed here. Create one with physics_capsule_shape_create(), see physics_shape for an overview of the shapes.
Properties
half_height
Half of the height of the straight part of the capsule.
const float physics_capsule_shape::half_height;
radius
The radius of the capsule.
const float physics_capsule_shape::radius;
physics_character
A physics_character is a body in a physics_world made for the player or another person or creature that walks around. It is a real physical body that collides with the world, is pulled down by gravity, stands on floors, and slides along walls, but unlike a crate it can't be knocked over, and it never rotates by itself. Instead of pushing it with forces you move it by setting its linear_velocity, as you would give a person a walking speed, and the physics engine keeps it out of walls and on the ground.
physics_character@ physics_character(physics_world@ world, physics_shape@ shape, const vector&in position, const quaternion&in rotation = IDENTITY_QUATERNION, float mass = 80.0f, float friction = 0.2f, uint16 layer = PHYSICS_LAYER_MOVING);physics_character@ physics_character(physics_world@ world, float height, float radius, const vector&in position, float mass = 80.0f, float friction = 0.2f, uint16 layer = PHYSICS_LAYER_MOVING);
Arguments:
- physics_world@ world: the world the character lives in.
- physics_shape@ shape (1): the shape of the character.
- float height (2): the total height of the character in meters, which must be at least twice the radius.
- float radius (2): the radius of the character's capsule in meters.
- const vector&in position: where to put the character. With the second constructor this is the point on the floor below the character's center, with the first it is the origin of the shape.
- const quaternion&in rotation = IDENTITY_QUATERNION (1): how the shape is turned.
- float mass = 80.0f: the mass of the character in kilograms, which determines how hard it pushes things it walks into.
- float friction = 0.2f: how much the character grips the surfaces it touches.
- uint16 layer = PHYSICS_LAYER_MOVING: the layer of the character, see the
physics_object_layerenum.
Remarks:
The second constructor builds a capsule, a good shape for a standing person that slides smoothly along walls, and stands it up along the direction that is opposite of the world's gravity, so set the world's gravity before creating characters. It returns null if the radius is not positive or the height is less than twice the radius. The first constructor returns null if the world or shape is null.
The character's up direction, set when it is created, is the direction that its ground detection considers up and that slopes are measured against. A character cannot turn, so to rotate the listener or other things with the player you track the direction yourself.
A character is in a physics_world like any other body, which is updated with physics_world::update(). After each update, the character works out what it is standing on, and the ground_state, supported and other ground properties show the result. Setting linear_velocity while on the ground makes the character walk, but remember it also holds the character's falling speed, so keep the up component when you set it, otherwise the character will stop falling:
vector v = c.linear_velocity;
c.linear_velocity = vector(walk_x, walk_y, v.z);
Characters are acoustically transparent by default, so that the listener and the sounds the character makes, which are usually inside its shape, are not blocked by it in a sound_environment. See the acoustically_transparent property.
Example:
void main() {
physics_world world;
world.create_and_add_body(physics_box_shape_create(vector(20, 20, 0.5)), vector(0, 0, -0.5), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING);
physics_character player(world, 1.8, 0.3, vector(0, 0, 2)); // A person 1.8 meters tall dropped from 2 meters up.
for (int i = 0; i < 120; i++) world.update(1.0 / 60);
alert("Character", "The character is standing at a height of " + player.position.z + (player.supported ? " on the ground." : " in the air."));
}
Methods
activate
Wake the character up.
void physics_character::activate();
Remarks:
Characters that stand still fall asleep like other bodies.
add_impulse
Give the character a sudden push.
void physics_character::add_impulse(const vector&in impulse);
Arguments:
- const vector&in impulse: the impulse in kilogram meters per second. The speed the character gains is this divided by its mass.
Remarks:
A jump can be made by an impulse in the up direction.
add_linear_velocity
Add to the character's velocity.
void physics_character::add_linear_velocity(const vector&in velocity);
Arguments:
- const vector&in velocity: the velocity to add in meters per second.
is_slope_too_steep
Check whether a surface is too steep for the character to stand on.
bool physics_character::is_slope_too_steep(const vector&in normal) const;
Arguments:
- const vector&in normal: the direction the surface faces.
Returns:
bool: true if a surface with this normal is steeper than max_slope_angle.
set_shape
Change the character's shape, for example to crouch.
bool physics_character::set_shape(physics_shape@ shape, float max_penetration_depth = FLOAT_MAX);
Arguments:
- physics_shape@ shape: the new shape.
- float max_penetration_depth = FLOAT_MAX: the most the new shape may overlap the world for the change to be allowed. By default there is no limit.
Returns:
bool: true if the shape was changed, false if the new shape would overlap the world too much, such as when trying to stand up under a low ceiling.
Properties
acoustically_transparent
Whether sound passes through the character's body without being blocked.
bool physics_character::acoustically_transparent;
Remarks:
This is true by default. The player's listener and the sounds that characters make are inside their bodies, so if the characters blocked acoustic rays, every sound would be muffled by the person making it. Set it to false if you want a character to block sound, for example a large monster.
body
The id of the character's body in its world.
const physics_body_id physics_character::body;
Remarks:
This lets you use the character with the methods of the world that take a body id, such as physics_world::get_friction().
center_of_mass_position
The position of the character's center of mass.
const vector physics_character::center_of_mass_position;
ground_body
The body the character is standing on.
const physics_body_id physics_character::ground_body;
Remarks:
This is an invalid id when the character is not supported.
ground_material
The material of the surface the character is standing on.
const physics_material@ physics_character::ground_material;
Remarks:
This is null when the character is in the air or the shape underfoot has no material. It is what you would use to choose the sound of a footstep, for example by the material's name.
ground_normal
The direction the ground the character is standing on is facing, with a length of 1.
const vector physics_character::ground_normal;
Remarks:
For flat ground this is the up direction. This is only meaningful while the character is supported.
ground_position
The point of contact with the ground the character is standing on.
const vector physics_character::ground_position;
Remarks:
This is only meaningful while the character is supported.
ground_state
What the character is standing on, if anything.
const physics_ground_state physics_character::ground_state;
Remarks:
See the physics_ground_state enum. This is updated by physics_world::update().
ground_velocity
How fast the ground the character is standing on is moving.
const vector physics_character::ground_velocity;
Remarks:
This is zero for static ground and non zero on a moving platform, which a character should add to its own movement to be carried along.
layer
The layer the character is in.
uint16 physics_character::layer;
Remarks:
See the physics_object_layer enum.
linear_velocity
How fast and in which direction the character is moving, in meters per second.
vector physics_character::linear_velocity;
Remarks:
Set this to make the character walk or jump. It includes the speed of falling in the up direction, so when walking along the ground set only the components that are not up. The character is stopped by walls and kept on the floor by the simulation, so the speed it actually moves at can differ from what you set.
max_separation_distance
How far in meters from the character's shape a contact can be and still count when working out what the character is standing on.
float physics_character::max_separation_distance;
Remarks:
The default is 0.05. Increase it if the character loses contact with the ground when moving down slopes or stairs.
max_slope_angle
The steepest slope the character can stand on, in radians.
float physics_character::max_slope_angle;
Remarks:
The default is 50 degrees (about 0.87 radians). On steeper ground the character slides and ground_state is PHYSICS_GROUND_STATE_ON_STEEP_GROUND.
position
The position of the character.
vector physics_character::position;
Remarks:
For a character made with a height and a radius this is the point on the floor underneath the character, otherwise it is the origin of the character's shape. Setting it moves the character there instantly.
Example:
void main() {
physics_world world;
physics_character c(world, 1.8, 0.3, vector(0, 0, 0));
c.position = vector(10, 5, 0);
alert("Position", "The character is at " + c.position.x + ", " + c.position.y + ", " + c.position.z);
}
rotation
How the character's body is turned.
quaternion physics_character::rotation;
Remarks:
Characters don't rotate on their own, only by setting this.
shape
The shape of the character.
const physics_shape@ physics_character::shape;
supported
Whether the character is standing on ground that supports it.
const bool physics_character::supported;
Remarks:
This is the usual check for whether a character may jump or is falling.
up
The direction the character considers to be up.
vector physics_character::up;
Remarks:
It is the direction opposite to the world's gravity at the time the character was created, and used to work out what is ground and how steep slopes are. It is set with a vector of any length, which is normalized.
world
The physics_world the character lives in.
const physics_world@ physics_character::world;
physics_convex_shape
The base class of the shapes that have no dents, which are all of the shapes that can be made apart from planes. It is derived from physics_shape, and has all of its properties as well as the ones listed here. See physics_shape for the kinds of shape.
Properties
density
The density of the shape in kilograms per cubic meter.
float physics_convex_shape::density;
Remarks:
The default is 1000, the density of water. The mass of a dynamic body is its shape's volume times density, so the heavier a thing should be, the higher this should be before the body is created. Changing it does not change bodies that were already made with the shape.
material
The material of the shape.
const physics_material@ physics_convex_shape::material;
Remarks:
This is null if the shape was created without one.
physics_cylinder_shape
A cylinder. It is derived from physics_convex_shape and physics_shape and has all of their properties, as well as those listed here. Create one with physics_cylinder_shape_create(), see physics_shape for an overview of the shapes.
Properties
convex_radius
How much the edges of the cylinder are rounded.
const float physics_cylinder_shape::convex_radius;
half_height
Half of the height of the cylinder.
const float physics_cylinder_shape::half_height;
radius
The radius of the cylinder.
const float physics_cylinder_shape::radius;
physics_plane_shape
A flat surface that is solid behind it, useful for floors and the outer walls of a map. It is derived from physics_shape and has all of its properties, as well as those listed here. Create one with physics_plane_shape_create(), see physics_shape for an overview of the shapes.
A plane shape can only be used for static and kinematic bodies.
Properties
half_extent
How far the plane goes in every direction from the point on it that is closest to the shape's origin, which is also how deep the solid part behind the plane is.
const float physics_plane_shape::half_extent;
Remarks:
Nothing collides with the plane outside of this area, which is what the shape's local_bounds covers.
material
The material of the shape.
const physics_material@ physics_plane_shape::material;
Remarks:
This is null if the shape was created without one.
plane
The plane that is the surface of the shape, relative to the shape's origin.
const plane physics_plane_shape::plane;
physics_shape
A physics_shape describes the form of a body, which decides what it collides with. It is made with one of the physics_*_shape_create() functions, such as physics_box_shape_create(), and given to physics_world::create_and_add_body(), and the same shape may be given to any number of bodies.
Each kind of shape has its own class that is derived from physics_shape, most of them through physics_convex_shape, so a shape such as a physics_box_shape has all the properties of the classes it derives from. Handles can be cast between them, cast<physics_box_shape>(shape) returning null if the shape is of a different kind, and a shape of any kind may be passed where a physics_shape is expected.
The kinds of shape are:
- physics_sphere_shape: a ball, with a
radius. - physics_box_shape: a box, with a
half_extent. - physics_capsule_shape: a cylinder with half spheres on its ends, with a
half_heightand aradius. - physics_cylinder_shape: a cylinder with a
half_heightand aradius. - physics_tapered_capsule_shape: a capsule whose ends have a
top_radiusand abottom_radius. - physics_tapered_cylinder_shape: a cylinder whose ends have a
top_radiusand abottom_radius. - physics_plane_shape: a flat surface with a
plane, that is solid behind it, which is good for floors.
All of these but the plane are convex, meaning that they have no dents, and are derived from physics_convex_shape. A plane shape can only be used for static and kinematic bodies. Any shape can also be stretched into a new physics_shape with scaled(), and given to mixer::set_shape() so that a sound fills it. Shapes are measured in meters. Shapes whose size is described along an axis, the capsule and cylinders, are aligned with the y axis of the shape, and a body that is to stand up in the world, where z is up, needs a rotation to do so, such as quaternion_from_axis_angle(vector(1, 0, 0), 1.5707964).
The properties that are specific to each kind of shape are listed in the documentation of the creation function of that kind.
Methods
cast_ray
Cast a ray against the shape alone, finding where it first hits.
bool physics_shape::cast_ray(const vector&in origin, const vector&in direction, float&out hit_fraction) const;
Arguments:
const vector&in origin: where the ray starts, relative to the shape's origin.
const vector&in direction: the direction and length of the ray, so the ray ends at
origin + direction.float&out hit_fraction: set to how far along the ray the hit is, from 0 at its origin to 1 at its end, if there is one.
Returns:
bool: true if the ray hit the shape.
Remarks:
The shape is treated as solid, so a ray starting inside it hits at a fraction of 0. To cast rays against the bodies in a world, use physics_world::cast_ray().
Example:
void main() {
physics_sphere_shape@ target = physics_sphere_shape_create(1);
float fraction;
if (target.cast_ray(vector(-10, 0, 0), vector(20, 0, 0), fraction)) alert("Hit", "The ray hit the sphere " + fraction * 20 + " meters from where it started."); // 9 meters.
}
closest_point
Find the point of the shape closest to another point.
vector@ physics_shape::closest_point(const vector&in point) const;
Arguments:
- const vector&in point: the point to measure from, relative to the shape's origin.
Returns:
vector@: the point on the surface of the shape that is closest to the given point, or the given point itself if it is inside the shape.
Remarks:
The shape here isn't in the world, so the point is relative to the shape's own origin and the result is too. To find the closest point of a body in the world, use physics_world::get_closest_point(), which takes the body's position and rotation into account.
Example:
void main() {
physics_box_shape@ crate = physics_box_shape_create(vector(1, 1, 1));
alert("Closest point", "The closest point of the crate to a point 5 meters east of it is " + crate.closest_point(vector(5, 0, 0)));
}
contains_point
Check whether a point is inside the shape.
bool physics_shape::contains_point(const vector&in point) const;
Arguments:
- const vector&in point: the point to check, relative to the shape's origin.
Returns:
bool: true if the point is inside the shape.
Remarks:
Shapes are treated as solid, and for a plane shape everything behind the plane is inside it. The shape is not in the world, so to check a point in the world against a body, subtract the body's position first and undo its rotation.
Example:
void main() {
physics_box_shape@ room = physics_box_shape_create(vector(5, 4, 1.5));
vector player(3, 2, 0);
alert("Room", room.contains_point(player) ? "The player is in the room." : "The player is outside.");
}
is_valid_scale
Check whether the shape can be stretched by a scale exactly, without making a compound of several shapes.
bool physics_shape::is_valid_scale(const vector&in scale) const;
Arguments:
- const vector&in scale: how much to stretch along the x, y and z axes, where 1 is no change.
Returns:
bool: true if scaled() can stretch the shape by this scale directly.
Remarks:
Spheres and capsules can only be scaled by the same amount along every axis, cylinders can only be scaled by the same amount along x and z, and boxes can be scaled any way. No part of a scale may be 0.
make_scale_valid
Get the closest scale to a given one that the shape can be stretched by exactly.
vector@ physics_shape::make_scale_valid(const vector&in scale) const;
Arguments:
- const vector&in scale: the scale that is wanted.
Returns:
vector@: a scale for which is_valid_scale() is true.
Remarks:
For example a sphere can only be scaled evenly, so vector(1, 2, 3) becomes the same amount along every axis. Compare the result with the scale you wanted to find out whether the shape will look very different from what you expected.
scaled
Make a new shape that is this one stretched along each axis.
physics_shape@ physics_shape::scaled(const vector&in scale) const;
Arguments:
- const vector&in scale: how much to stretch along the x, y and z axes, where 1 is no change and 2 is twice the size. A negative value mirrors the shape along that axis.
Returns:
physics_shape@: the scaled shape, or null if it could not be made, such as when the scale is zero.
Remarks:
The shape this is called on is not changed. Unless the scale is 1, the result is usually a shape of type PHYSICS_SHAPE_DECORATED and sub type PHYSICS_SHAPE_SCALED that wraps the original, so it can't be cast to the kind of shape it was made from. A scale that is_valid_scale() says the shape can't take is approximated, see make_scale_valid().
This makes it easy to use one shape at several sizes, but if a shape of a particular size is all that's needed, creating it at that size is faster to simulate.
Example:
void main() {
physics_sphere_shape@ pebble = physics_sphere_shape_create(0.1);
physics_shape@ boulder = pebble.scaled(vector(20, 20, 20));
alert("Boulder", "The boulder is " + boulder.local_bounds.size.x + " meters across."); // 4 meters.
}
Properties
center_of_mass
The center of mass of the shape, relative to its origin.
const vector physics_shape::center_of_mass;
Remarks:
This is the origin for most shapes, but not for those that are heavier at one end, such as a tapered cylinder, whose center of mass is closer to its wider end. Bodies turn around their center of mass.
inner_radius
The radius of the largest sphere that fits entirely inside the shape.
const float physics_shape::inner_radius;
Remarks:
This is a measure of how far a body with the shape can safely move in one step without risking passing through something thin. A box with a half extent of vector(1, 2, 3) has an inner radius of 1, and a plane has an inner radius of 0.
local_bounds
The smallest box that contains the shape, around the shape's own origin.
const aabb physics_shape::local_bounds;
Remarks:
This is not rotated or moved, for the box of a body in the world use physics_world::get_world_space_bounds().
mass
The mass in kilograms that a dynamic body made with the shape has.
const float physics_shape::mass;
Remarks:
For a convex shape this is its volume multiplied by its density. Shapes that must be static, such as planes, have no mass.
must_be_static
Whether the shape can't be used for dynamic bodies.
const bool physics_shape::must_be_static;
Remarks:
This is true for plane shapes and anything made from them. physics_world::create_and_add_body() fails when such a shape is given with PHYSICS_BODY_DYNAMIC.
sub_type
The specific kind of the shape, a value of the physics_shape_sub_type enum.
const uint8 physics_shape::sub_type;
Remarks:
For example PHYSICS_SHAPE_BOX or PHYSICS_SHAPE_CAPSULE.
type
The general category of the shape, a value of the physics_shape_type enum.
const uint8 physics_shape::type;
Remarks:
Shapes made by the physics_*_shape_create() functions are PHYSICS_SHAPE_CONVEX, apart from plane shapes, which are PHYSICS_SHAPE_PLANE.
volume
The volume of the shape in cubic meters.
const float physics_shape::volume;
Remarks:
This with the density determines the mass of dynamic bodies made with the shape.
physics_sphere_shape
A ball. It is derived from physics_convex_shape and physics_shape and has all of their properties, as well as those listed here. Create one with physics_sphere_shape_create(), see physics_shape for an overview of the shapes.
Properties
radius
The radius of the sphere.
const float physics_sphere_shape::radius;
physics_tapered_capsule_shape
A capsule whose ends have different radii. It is derived from physics_convex_shape and physics_shape and has all of their properties, as well as those listed here. Create one with physics_tapered_capsule_shape_create(), see physics_shape for an overview of the shapes.
Properties
bottom_radius
The radius of the bottom end.
const float physics_tapered_capsule_shape::bottom_radius;
half_height
Half of the height of the tapered part of the capsule.
const float physics_tapered_capsule_shape::half_height;
top_radius
The radius of the top end.
const float physics_tapered_capsule_shape::top_radius;
physics_tapered_cylinder_shape
A cylinder whose ends have different radii. It is derived from physics_convex_shape and physics_shape and has all of their properties, as well as those listed here. Create one with physics_tapered_cylinder_shape_create(), see physics_shape for an overview of the shapes.
Properties
bottom_radius
The radius of the bottom end.
const float physics_tapered_cylinder_shape::bottom_radius;
convex_radius
How much the edges of the tapered cylinder are rounded.
const float physics_tapered_cylinder_shape::convex_radius;
half_height
Half of the height of the tapered cylinder.
const float physics_tapered_cylinder_shape::half_height;
top_radius
The radius of the top end.
const float physics_tapered_cylinder_shape::top_radius;
physics_transform
A physics_transform is a position and a rotation together, as returned by physics_world::get_transform(). It is a plain value that is copied when assigned.
physics_transform();physics_transform(const vector&in position, const quaternion&in rotation);physics_transform(const physics_transform&in other);
Arguments (2):
- const vector&in position: the position.
- const quaternion&in rotation: the rotation.
Arguments (3):
- const physics_transform&in other: the transform to copy.
Remarks:
A default constructed transform has no position and no rotation, which is IDENTITY_TRANSFORM. Transforms can be compared with ==. Besides the position and rotation properties, the plain numbers they are made of are available as px, py and pz for the position and qx, qy, qz and qw for the rotation.
Properties
position
The position part of the transform.
vector physics_transform::position;
rotation
The rotation part of the transform.
quaternion physics_transform::rotation;
physics_world
A physics_world is a simulation of rigid bodies, solid objects that fall, collide, bounce and slide, that you step forward in time from your game loop. It is NVGT's wrapper around the Jolt physics engine, and can also be used as the world that sound_environment (from the nvgt_phonon plugin) traces its occlusion and reflections through.
physics_world@ physics_world(uint max_bodies = 1024, uint max_body_pairs = 1024, uint max_contact_constraints = 1024);
Arguments:
- uint max_bodies = 1024: the most bodies that can exist in the world at once, including static ones such as walls. Adding a body beyond this fails.
- uint max_body_pairs = 1024: the most pairs of bodies that may be close enough to need a collision check in one update. Raise this if you have many bodies packed together.
- uint max_contact_constraints = 1024: the most contacts that may be resolved in a single update. Raise this if you have many bodies resting on or against each other.
Remarks:
The three limits are reserved when the world is created, so there is no point in making them much larger than you need, but if they are too low bodies will be missing or will pass through each other with no error. Worlds that model a few characters and a level are fine with the defaults, while a world with thousands of objects needs a lot more.
The basics
A world is made of bodies. A body is a shape (a sphere, box, capsule or cylinder, see for example physics_box_shape_create()) that has a position and rotation and a motion type from the physics_body_type enum:
- PHYSICS_BODY_STATIC bodies never move, which makes them cheap and is what you want for floors, walls and other parts of a level.
- PHYSICS_BODY_DYNAMIC bodies are moved by the simulation, which pulls them down with gravity and pushes them around when they collide. Use them for crates, balls, debris and anything else that should obey physics.
- PHYSICS_BODY_KINEMATIC bodies are moved only by your script, with
move_kinematic()orset_position(), but they push dynamic bodies out of the way. Use them for things such as moving platforms and doors.
Bodies are not objects in your script. You get a physics_body_id back from create_and_add_body() and pass it to the world's methods to read or change the body, so keep the ids of any bodies you need to find again, and remove them with remove_and_destroy_body() when you are done.
Every body is also in a layer, either PHYSICS_LAYER_NON_MOVING for static bodies or PHYSICS_LAYER_MOVING for everything else. Non moving bodies are never checked against each other, which saves a great deal of work, so a static body should always be in the non moving layer.
Units and directions
Distances are in meters, time in seconds and mass in kilograms, though you are free to treat a unit as something else in your game as long as you are consistent, and gravity, speeds and forces are scaled to match. NVGT uses a z up coordinate system, with x to the right, y forward and z up, so a new world's gravity points down the z axis, (0, 0, -9.81), which is that of the earth in meters per second squared. Change it with the gravity property.
Running the simulation
Nothing moves until you call update() with the time that has passed, normally once per frame of your game loop. For stable results the time should be small, so a delta of more than about 1/60th of a second should be split over multiple collision steps, or the update called several times. Bodies that come to rest go to sleep and cost almost nothing until something touches them, see the num_active_bodies property.
To find out when bodies hit each other, call set_contact_listener(), whose callbacks run during update() on the thread that called it. To find what is in a direction from a point, use cast_ray().
Example:
void main() {
physics_world world;
// A floor 1 meter thick, whose top is at z 0, which never moves.
world.create_and_add_body(physics_box_shape_create(vector(50, 50, 0.5)), vector(0, 0, -0.5), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING);
// A ball with a radius of half a meter dropped from 10 meters up.
physics_body_id ball = world.create_and_add_body(physics_sphere_shape_create(0.5), vector(0, 0, 10), IDENTITY_QUATERNION, PHYSICS_BODY_DYNAMIC);
for (int i = 0; i < 180; i++) world.update(1.0 / 60); // Three seconds of simulation.
vector pos = world.get_position(ball);
alert("Ball", "The ball came to rest at a height of " + pos.z);
}
Methods
activate_body
Wake a body up.
void physics_world::activate_body(const physics_body_id&in id);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Remarks:
Sleeping bodies wake automatically when something touches them, but not when you take away what they were resting on without telling the simulation.
add_angular_impulse
Give a body a sudden spin.
void physics_world::add_angular_impulse(const physics_body_id&in id, const vector&in impulse);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in impulse: the angular impulse, whose direction is the axis the body starts to turn around.
Remarks:
This changes the body's angular velocity immediately and once.
add_force
Push a body for the duration of the next update.
void physics_world::add_force(const physics_body_id&in id, const vector&in force);void physics_world::add_force(const physics_body_id&in id, const vector&in force, const vector&in point);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in force: the force in newtons, which for a body of 1 kilogram accelerates it by 1 meter per second squared.
- const vector&in point (2): the point in the world to push at. A push away from the body's center of mass also turns it. Without this the push goes through the center of mass.
Remarks:
A force acts for a single update and is then forgotten, so to keep pushing something, such as with an engine, call this every frame before update(). For a sudden push such as an explosion or a jump, use add_impulse().
add_impulse
Give a body a sudden push.
void physics_world::add_impulse(const physics_body_id&in id, const vector&in impulse);void physics_world::add_impulse(const physics_body_id&in id, const vector&in impulse, const vector&in point);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in impulse: the impulse in kilogram meters per second. The velocity the body gains is this divided by its mass.
- const vector&in point (2): the point in the world to push at, which can also make the body spin.
Remarks:
An impulse changes the body's velocity immediately and once, unlike a force which acts over the next update.
add_linear_velocity
Add to a body's velocity.
void physics_world::add_linear_velocity(const physics_body_id&in id, const vector&in v);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in v: the velocity to add in meters per second.
add_torque
Twist a body for the duration of the next update.
void physics_world::add_torque(const physics_body_id&in id, const vector&in torque);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in torque: the torque in newton meters, whose direction is the axis to turn around.
Remarks:
Like add_force(), a torque acts for a single update and is then forgotten, so apply it every frame to keep spinning something. For a sudden spin use add_angular_impulse().
apply_buoyancy_impulse
Push and slow a body the way water would, if it is under the surface of a fluid.
bool physics_world::apply_buoyancy_impulse(const physics_body_id&in id, const vector&in surface_pos, const vector&in surface_normal, float buoyancy, float linear_drag, float angular_drag, const vector&in fluid_velocity, const vector&in gravity, float delta_time);
Arguments:
const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().const vector&in surface_pos: any point on the surface of the fluid.
const vector&in surface_normal: the direction the surface faces, which is up for a lake.
float buoyancy: how much the fluid pushes the body up. 1 makes the body float at neutral buoyancy, neither sinking nor rising, 0 gives no push and higher values make it rise.
float linear_drag: how much the fluid slows the body's movement, from 0 for none to 1 for one that would stop it within a second.
float angular_drag: how much the fluid slows the body's spinning, on the same scale.
const vector&in fluid_velocity: the speed and direction the fluid itself is moving, for a river for example. Use
vector(0, 0, 0)for still water.const vector&in gravity: the gravity to push against, normally the world's.
float delta_time: the time of the step, normally what you pass to
update().
Returns:
bool: true if the body was in the fluid and an impulse was applied, false if it was above the surface.
Remarks:
There are no fluids in a physics_world, so to simulate water you call this every frame for each body that could be in it, before update(), with the surface of the water.
Example:
void main() {
physics_world world;
physics_body_id ball = world.create_and_add_body(physics_sphere_shape_create(0.5), vector(0, 0, -1), IDENTITY_QUATERNION, PHYSICS_BODY_DYNAMIC);
for (int i = 0; i < 120; i++) {
// Water with its surface at z 0, where the ball floats upwards.
world.apply_buoyancy_impulse(ball, vector(0, 0, 0), vector(0, 0, 1), 1.5, 0.5, 0.5, vector(0, 0, 0), world.gravity, 1.0 / 60);
world.update(1.0 / 60);
}
alert("Ball", "The ball is at a height of " + world.get_position(ball).z);
}
cast_ray
Find the first body hit by a ray.
bool physics_world::cast_ray(const vector&in origin, const vector&in direction, physics_body_id&out hit_body, float&out hit_fraction) const;
Arguments:
const vector&in origin: where the ray starts.
const vector&in direction: the direction the ray travels, whose length is also the length of the ray.
physics_body_id&out hit_body: receives the first body the ray hit.
float&out hit_fraction: receives how far along the ray the hit was, from 0 at the origin to 1 at the end of the direction vector.
Returns:
bool: true if a body was hit, false if the ray reached its end without touching anything.
Remarks:
The point that was hit is origin + direction * hit_fraction. Casting a ray from a point towards another and checking whether anything is in the way is a simple line of sight check.
Example:
void main() {
physics_world world;
world.create_and_add_body(physics_box_shape_create(vector(0.5, 5, 5)), vector(10, 0, 0), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING); // A wall 10 meters to the right.
physics_body_id hit;
float fraction;
vector start(0, 0, 0), direction(20, 0, 0); // A ray 20 meters long.
if (world.cast_ray(start, direction, hit, fraction)) alert("Ray", "Hit a wall " + fraction * 20 + " meters away.");
else alert("Ray", "Nothing was hit.");
}
create_and_add_body
Create a body and add it to the world.
physics_body_id physics_world::create_and_add_body(physics_shape@ shape, const vector&in position, const quaternion&in rotation, physics_body_type motion_type, uint16 layer = PHYSICS_LAYER_MOVING, physics_activation activation = PHYSICS_ACTIVATE);
Arguments:
physics_shape@ shape: the shape of the body, made with one of the
physics_*_shape_create()functions. The same shape can be given to any number of bodies.const vector&in position: where to put the body, in the world.
const quaternion&in rotation: how to turn the body, or
IDENTITY_QUATERNIONfor none.physics_body_type motion_type: whether the body is static, kinematic or dynamic, see the
physics_body_typeenum.uint16 layer = PHYSICS_LAYER_MOVING: the layer to put the body in,
PHYSICS_LAYER_NON_MOVINGfor static bodies andPHYSICS_LAYER_MOVINGfor the others, see thephysics_object_layerenum.physics_activation activation = PHYSICS_ACTIVATE: whether the body starts awake, see the
physics_activationenum.
Returns:
physics_body_id: the id of the new body, which is invalid (its is_invalid property is true) if the body could not be created, such as when the shape is null, the shape must be static (see physics_shape::must_be_static) and the motion type is PHYSICS_BODY_DYNAMIC, or the world already has its maximum number of bodies.
Remarks:
The position is the origin of the shape, which for the built in shapes is its center. A box created with a half extent of vector(50, 50, 0.5) is 100 meters wide and long and 1 meter thick, so its center must be 0.5 below the surface that things should rest on.
A body takes its friction and restitution from the physics_material its shape was made with, or has a friction of 0.2 and a restitution of 0 if the shape has none, and these can be changed afterwards with set_friction() and set_restitution(). A dynamic body gets its mass from the volume of its shape.
Example:
void main() {
physics_world world;
physics_body_id floor = world.create_and_add_body(physics_box_shape_create(vector(20, 20, 0.5)), vector(0, 0, -0.5), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING);
physics_body_id crate = world.create_and_add_body(physics_box_shape_create(vector(0.5, 0.5, 0.5)), vector(0, 0, 3), IDENTITY_QUATERNION, PHYSICS_BODY_DYNAMIC);
if (crate.is_invalid) alert("Error", "The crate could not be created.");
else alert("Bodies", "The world now has " + world.num_bodies + " bodies.");
}
deactivate_body
Put a body to sleep.
void physics_world::deactivate_body(const physics_body_id&in id);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Remarks:
A sleeping body does not move or cost anything to simulate until it is touched by an awake body or activated.
destroy_body
Free a body that has already been removed from the world.
void physics_world::destroy_body(const physics_body_id&in id);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Remarks:
The body must have been removed with remove_body() first, and its id can't be used again afterwards. Any user data attached to the body is released.
get_angular_velocity
Get how fast and around which axis a body is spinning.
vector@ physics_world::get_angular_velocity(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
vector@: the axis of the spin, whose length is the speed in radians per second.
get_center_of_mass_position
Get the position of a body's center of mass.
vector@ physics_world::get_center_of_mass_position(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
vector@: the position in the world.
Remarks:
This differs from get_position() for shapes that aren't centered on their origin. It is where forces act on the body when they are applied without a point.
get_closest_point
Find the point of a body closest to a point in the world.
vector@ physics_world::get_closest_point(const physics_body_id&in id, const vector&in point) const;
Arguments:
const physics_body_id&in id: the body to measure to.
const vector&in point: the point to measure from, such as the player's position.
Returns:
vector@: the point on the surface of the body closest to the given point, or the given point itself if it is inside the body or the body doesn't exist.
Remarks:
This takes the body's position, rotation and shape into account, so it answers questions such as how far the player is from a wall, rather than from its center, or where the nearest edge of an object they are tracking is. The distance to the body is the length of the difference between the two points, which is 0 when the point is inside it.
A sound played at the returned point is heard from the nearest part of the body, which gives the player a sense of how large it is and where its edges are. To have a sound fill a shape all the time, see mixer::set_shape().
Example:
void main() {
physics_world world;
physics_body_id wall = world.create_and_add_body(physics_box_shape_create(vector(10, 0.5, 3)), vector(0, 10, 3), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING);
vector player(4, 0, 1);
vector nearest = world.get_closest_point(wall, player);
alert("Wall", "The nearest part of the wall is at " + nearest + ", " + round((nearest - player).length(), 1) + " meters away.");
sound_play("C:/Windows/media/ding.wav", nearest); // A ping from the nearest part of the wall.
wait(1000);
}
get_friction
Get how much a body grips the things it slides against.
float physics_world::get_friction(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
float: the friction, where 0 is as slippery as ice and 1 is very grippy.
get_gravity_factor
Get how strongly gravity affects a body.
float physics_world::get_gravity_factor(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
float: the factor, where 1 is normal gravity.
get_linear_velocity
Get how fast and in which direction a body is moving.
vector@ physics_world::get_linear_velocity(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
vector@: the velocity in meters per second.
get_max_angular_velocity
Get the fastest a body can spin.
float physics_world::get_max_angular_velocity(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
float: the limit in radians per second.
Remarks:
The default is about 47 radians per second, a little over seven turns.
get_max_linear_velocity
Get the fastest a body can move.
float physics_world::get_max_linear_velocity(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
float: the speed limit in meters per second.
Remarks:
The default is 500.
get_motion_type
Get whether a body is static, kinematic or dynamic.
physics_body_type physics_world::get_motion_type(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
physics_body_type: the motion type of the body.
get_position
Get the position of a body.
vector@ physics_world::get_position(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
vector@: the position of the body's origin in the world.
get_restitution
Get how bouncy a body is.
float physics_world::get_restitution(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
float: the restitution.
get_rotation
Get the rotation of a body.
quaternion@ physics_world::get_rotation(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
quaternion@: the rotation of the body.
get_transform
Get the position and rotation of a body together.
physics_transform physics_world::get_transform(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
physics_transform: the body's position and rotation.
Example:
void main() {
physics_world world;
physics_body_id crate = world.create_and_add_body(physics_box_shape_create(vector(0.5, 0.5, 0.5)), vector(1, 2, 3), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING);
physics_transform t = world.get_transform(crate);
alert("Transform", "The crate is at " + t.position);
}
get_user_data
Retrieve the value attached to a body with set_user_data().
any@ physics_world::get_user_data(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
any@: the stored value, or null if there is none.
get_world_space_bounds
Get the smallest axis aligned box that contains a body.
aabb@ physics_world::get_world_space_bounds(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
aabb@: the box in world coordinates.
Remarks:
The box is recalculated from the body's shape and rotation, so for a rotated body it is larger than the body itself.
Example:
void main() {
physics_world world;
physics_body_id crate = world.create_and_add_body(physics_box_shape_create(vector(1, 2, 3)), vector(10, 0, 0), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING);
aabb bounds = world.get_world_space_bounds(crate);
alert("Bounds", "From " + bounds.min + " to " + bounds.max);
}
is_active
Check whether a body is awake.
bool physics_world::is_active(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
bool: true if the body is awake, false if it is asleep or removed from the world.
Remarks:
Bodies fall asleep once they stop moving. See also num_active_bodies.
is_added
Check whether a body is currently part of the simulation.
bool physics_world::is_added(const physics_body_id&in id) const;
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Returns:
bool: true if the body has been added to the world and not removed.
move_kinematic
Move a kinematic body to a target over time so that it pushes other bodies along the way.
void physics_world::move_kinematic(const physics_body_id&in id, const vector&in target_pos, const quaternion&in target_rot, float delta_time);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in target_pos: where the body should be after delta_time.
- const quaternion&in target_rot: how the body should be turned after delta_time.
- float delta_time: the number of seconds it should take, normally the delta_time you are about to pass to
update().
Remarks:
This gives the body the velocity needed to arrive at the target during the next update, so moving platforms and doors carry and push the bodies they touch, which set_position() would not do.
optimize_broadphase
Rebuild the structure the world uses to find nearby bodies so that it is as quick as possible.
void physics_world::optimize_broadphase();
Remarks:
Call this once after adding a large number of bodies at the start of a level, for example every piece of static scenery, and before the first call to update(). There is no need to call it while the game runs.
remove_and_destroy_body
Remove a body from the world and free it.
void physics_world::remove_and_destroy_body(const physics_body_id&in id);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Remarks:
This is how you delete a body, such as when a crate is destroyed or a monster dies. The id can't be used again afterwards.
remove_body
Take a body out of the simulation without destroying it.
void physics_world::remove_body(const physics_body_id&in id);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body().
Remarks:
A removed body can't collide or move, and is no longer found by cast_ray(), but it still exists and still counts as one of the world's maximum bodies until it is destroyed with destroy_body(). In practice you will nearly always want remove_and_destroy_body().
set_angular_velocity
Set how fast and around which axis a body is spinning.
void physics_world::set_angular_velocity(const physics_body_id&in id, const vector&in v);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in v: the axis of the spin, whose length is the speed in radians per second.
set_contact_listener
Set the functions that are called when bodies start, keep and stop touching.
void physics_world::set_contact_listener(physics_contact_added_callback@ on_added, physics_contact_persisted_callback@ on_persisted, physics_contact_removed_callback@ on_removed);
Arguments:
physics_contact_added_callback@ on_added: called when two bodies begin to touch, or null.
physics_contact_persisted_callback@ on_persisted: called each update that two bodies remain in contact, or null.
physics_contact_removed_callback@ on_removed: called when two bodies stop touching, or null.
Remarks:
The signatures of the callbacks are:
void physics_contact_added_callback(const physics_body_id&in body1, const physics_body_id&in body2, const vector&in world_normal, float penetration_depth);
void physics_contact_persisted_callback(const physics_body_id&in body1, const physics_body_id&in body2, const vector&in world_normal, float penetration_depth);
void physics_contact_removed_callback(const physics_body_id&in body1, const physics_body_id&in body2);
The simulation may run on several threads, so contacts are queued while update() runs and the callbacks are called one after the other from update() once the simulation step is complete. This means they can safely do anything a script can do, but also that by then bodies have moved on a little from where they hit. The normal points from the first body to the second, and the penetration depth is how far they overlap.
Example:
void hit(const physics_body_id&in a, const physics_body_id&in b, const vector&in normal, float depth) {
screen_reader_speak("Bump!", true);
}
void main() {
physics_world world;
world.create_and_add_body(physics_box_shape_create(vector(20, 20, 0.5)), vector(0, 0, -0.5), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING);
world.create_and_add_body(physics_sphere_shape_create(0.5), vector(0, 0, 3), IDENTITY_QUATERNION, PHYSICS_BODY_DYNAMIC);
world.set_contact_listener(hit, null, null);
for (int i = 0; i < 120; i++) {
world.update(1.0 / 60);
wait(16);
}
}
set_friction
Set how much a body grips the things it slides against.
void physics_world::set_friction(const physics_body_id&in id, float v);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - float v: the friction, where 0 is as slippery as ice and 1 is very grippy.
Remarks:
When two bodies touch, their frictions are combined, so the surface with the greater friction counts for more. The default is 0.2.
set_gravity_factor
Set how strongly gravity affects a body.
void physics_world::set_gravity_factor(const physics_body_id&in id, float v);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - float v: the factor the world's gravity is multiplied by for this body. 1 is normal, 0 makes the body float, and a negative value makes it fall upwards.
set_linear_velocity
Set how fast and in which direction a body is moving.
void physics_world::set_linear_velocity(const physics_body_id&in id, const vector&in v);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in v: the new velocity in meters per second.
Remarks:
This replaces the body's velocity, including any it gained from falling. To add to it instead, use add_linear_velocity() or the force and impulse methods.
set_max_angular_velocity
Limit how fast a body can spin.
void physics_world::set_max_angular_velocity(const physics_body_id&in id, float v);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - float v: the limit in radians per second.
set_max_linear_velocity
Limit how fast a body can move.
void physics_world::set_max_linear_velocity(const physics_body_id&in id, float v);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - float v: the speed limit in meters per second.
Remarks:
A body that is going faster than this is slowed to the limit. Very fast bodies can pass through thin ones, so it can help to lower this.
set_motion_type
Change whether a body is static, kinematic or dynamic.
void physics_world::set_motion_type(const physics_body_id&in id, physics_body_type type, physics_activation activation = PHYSICS_ACTIVATE);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - physics_body_type type: the new motion type.
- physics_activation activation = PHYSICS_ACTIVATE: whether to wake the body up.
Remarks:
Changing a body to static freezes it where it is, and changing it back to dynamic lets it fall again, which is how you could make an object pick up-able. Remember that static bodies should be in the non moving layer, so a body that will ever be moved should be created in the moving layer.
set_position
Move a body to a position.
void physics_world::set_position(const physics_body_id&in id, const vector&in pos, physics_activation activation = PHYSICS_ACTIVATE);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in pos: the new position.
- physics_activation activation = PHYSICS_ACTIVATE: whether to wake the body up so that it reacts to its new surroundings.
Remarks:
The body jumps there instantly without colliding with anything on the way, and keeps its velocity, so for a dynamic body you may want to set_linear_velocity() to zero as well. To move a kinematic body so that it pushes things along the way use move_kinematic() instead.
set_position_and_rotation
Move and turn a body in one go.
void physics_world::set_position_and_rotation(const physics_body_id&in id, const vector&in pos, const quaternion&in rot, physics_activation activation = PHYSICS_ACTIVATE);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const vector&in pos: the new position.
- const quaternion&in rot: the new rotation.
- physics_activation activation = PHYSICS_ACTIVATE: whether to wake the body up.
set_restitution
Set how bouncy a body is.
void physics_world::set_restitution(const physics_body_id&in id, float v);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - float v: the restitution, where 0 means a body stops dead when it hits something and 1 means it bounces back with all the speed it came with.
Remarks:
The default is 0.
set_rotation
Turn a body to a rotation.
void physics_world::set_rotation(const physics_body_id&in id, const quaternion&in rot, physics_activation activation = PHYSICS_ACTIVATE);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - const quaternion&in rot: the new rotation.
- physics_activation activation = PHYSICS_ACTIVATE: whether to wake the body up.
set_shape
Change the shape of a body.
void physics_world::set_shape(const physics_body_id&in id, physics_shape@ shape, bool update_mass = true, physics_activation activation = PHYSICS_ACTIVATE);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - physics_shape@ shape: the new shape.
- bool update_mass = true: whether to recalculate the body's mass and the way it spins from the new shape. Leave this on unless you want to keep the old mass.
- physics_activation activation = PHYSICS_ACTIVATE: whether to wake the body up.
Remarks:
This is how a body grows, shrinks or changes form, such as a crate that breaks. Other bodies resting on a body whose shape changes are not woken up automatically. Nothing happens if the shape is null.
set_user_data
Attach a value of your own to a body.
void physics_world::set_user_data(const physics_body_id&in id, any@ data);
Arguments:
- const physics_body_id&in id: the body to operate on, as returned by
create_and_add_body(). - any@ data: the value to store, or null to clear it.
Remarks:
This is a convenient way to find the game object that a body belongs to, for example when a contact listener or a ray reports a body. It is released when the body is destroyed.
update
Advance the simulation by an amount of time.
void physics_world::update(float delta_time, int collision_steps = 1);
Arguments:
float delta_time: the number of seconds to advance by, normally the time since the last call.
int collision_steps = 1: how many steps the update is divided into for collision detection. Use more when delta_time is large, about one for each 1/60th of a second, otherwise fast objects can pass through thin ones.
Remarks:
Call this every frame of your game loop. Contact listener callbacks are dispatched before it returns, and characters are updated afterwards. For the most predictable results, call it with the same small value each time rather than with a variable frame time.
Example:
void main() {
physics_world world;
physics_body_id ball = world.create_and_add_body(physics_sphere_shape_create(0.5), vector(0, 0, 10), IDENTITY_QUATERNION, PHYSICS_BODY_DYNAMIC);
timer t;
int last = 0;
while (t.elapsed < 1000) {
wait(5);
world.update((t.elapsed - last) / 1000.0);
last = t.elapsed;
}
alert("Ball", "After about a second of falling the ball is at " + world.get_position(ball).z);
}
were_bodies_in_contact
Check whether two bodies were touching at the last update.
bool physics_world::were_bodies_in_contact(const physics_body_id&in a, const physics_body_id&in b) const;
Arguments:
- const physics_body_id&in a: the first body.
- const physics_body_id&in b: the second body.
Returns:
bool: true if the bodies were in contact.
Remarks:
To be told when contacts start and end rather than checking, use set_contact_listener().
Properties
gravity
The acceleration applied to every dynamic body each second, as a vector in meters per second squared.
vector physics_world::gravity;
Remarks:
The default is (0, 0, -9.81), which is earth's gravity pulling down along the z axis. Setting it to (0, 0, 0) gives a world without gravity, such as space. Individual bodies can be made to feel more or less of it with set_gravity_factor().
Characters take their up direction from the direction opposite gravity, so set the gravity before creating any.
Example:
void main() {
physics_world world;
world.gravity = vector(0, 0, -1.62); // The moon.
alert("Gravity", "Gravity pulls with " + world.gravity.z + " meters per second squared.");
}
num_active_bodies
The number of dynamic and kinematic bodies that are awake.
const uint physics_world::num_active_bodies;
Remarks:
Bodies that stop moving fall asleep, and stay that way until they are touched or activate_body() is called, and they cost almost nothing to simulate while they do. A low number compared to num_bodies means the world is settled.
num_bodies
The total number of bodies in the world, awake or asleep, static or moving.
const uint physics_world::num_bodies;
Enums
physics_activation
This is a list of the values that choose whether changing a body wakes it up, accepted by physics_world::create_and_add_body(), physics_world::set_position() and similar methods.
- PHYSICS_ACTIVATE: the body is awake after the operation and is simulated.
- PHYSICS_DONT_ACTIVATE: the body is left asleep if it was asleep (or starts asleep when created). It wakes when something touches it or
physics_world::activate_body()is called.
Bodies that stop moving fall asleep by themselves, which keeps big worlds cheap.
physics_body_type
This is a list of the ways a body can move, passed to physics_world::create_and_add_body(), physics_world::set_motion_type() and returned by physics_world::get_motion_type().
- PHYSICS_BODY_STATIC: the body never moves, and costs nothing to simulate. Use it for floors, walls and the rest of a level.
- PHYSICS_BODY_KINEMATIC: the body is moved only by your script, using
physics_world::move_kinematic()orphysics_world::set_position(), and is not affected by gravity or collisions, but pushes dynamic bodies. Use it for moving platforms and doors. - PHYSICS_BODY_DYNAMIC: the body is moved by the simulation, falling under gravity and bouncing off or pushing the bodies it collides with.
physics_ground_state
This is a list of the states a character can be in with respect to the ground, returned by physics_character::ground_state.
- PHYSICS_GROUND_STATE_ON_GROUND: the character is standing on ground that it can walk on.
- PHYSICS_GROUND_STATE_ON_STEEP_GROUND: the character is touching ground that is too steep to stand on, so it would slide down. See
physics_character::max_slope_angle. - PHYSICS_GROUND_STATE_NOT_SUPPORTED: the character is touching something below it, such as the edge of a ledge, that is not enough to support it.
- PHYSICS_GROUND_STATE_IN_AIR: the character is not touching anything below it.
physics_object_layer
This is a list of the layers a body can be put in, passed to physics_world::create_and_add_body(). Layers decide which bodies need to be checked against each other for collisions.
- PHYSICS_LAYER_NON_MOVING: for static bodies. Bodies in this layer collide only with those in the moving layer, never with each other, so a large static level costs very little.
- PHYSICS_LAYER_MOVING: for kinematic and dynamic bodies, which collide with everything.
A static body must be in the non moving layer, and a body that moves, or may be changed to move with physics_world::set_motion_type(), in the moving layer.
physics_shape_sub_type
This is a list of the specific kinds of shapes, the value of physics_shape::sub_type.
- PHYSICS_SHAPE_SPHERE: a ball.
- PHYSICS_SHAPE_BOX: a box.
- PHYSICS_SHAPE_TRIANGLE: a single triangle.
- PHYSICS_SHAPE_CAPSULE: a cylinder with half spheres on the ends.
- PHYSICS_SHAPE_CYLINDER: a cylinder.
- PHYSICS_SHAPE_TAPERED_CAPSULE: a capsule whose ends have different radii.
- PHYSICS_SHAPE_TAPERED_CYLINDER: a cylinder whose ends have different radii.
- PHYSICS_SHAPE_CONVEX_HULL: the smallest convex shape that contains a set of points.
- PHYSICS_SHAPE_STATIC_COMPOUND: a shape made of several others that does not change.
- PHYSICS_SHAPE_MUTABLE_COMPOUND: a shape made of several others that can change.
- PHYSICS_SHAPE_MESH_SUBTYPE: a shape made of triangles.
- PHYSICS_SHAPE_HEIGHT_FIELD_SUBTYPE: a shape made of a grid of heights.
- PHYSICS_SHAPE_ROTATED_TRANSLATED: another shape turned and moved.
- PHYSICS_SHAPE_SCALED: another shape stretched, as made by
physics_shape::scaled(). - PHYSICS_SHAPE_OFFSET_CENTER_OF_MASS: another shape whose center of mass is moved.
- PHYSICS_SHAPE_PLANE_SUBTYPE: a flat surface that is solid behind it.
Currently the shape creation functions make the sphere, box, capsule, cylinder, tapered capsule, tapered cylinder and plane shapes, and physics_shape::scaled() makes scaled shapes.
physics_shape_type
This is a list of the general categories a shape can be in, the value of physics_shape::type.
- PHYSICS_SHAPE_CONVEX: a shape without dents, such as a sphere, box, capsule or cylinder.
- PHYSICS_SHAPE_COMPOUND: a shape made of several others.
- PHYSICS_SHAPE_MESH: a shape made of triangles.
- PHYSICS_SHAPE_HEIGHT_FIELD: a shape made of a grid of heights, such as terrain.
- PHYSICS_SHAPE_DECORATED: a shape that changes another, such as one made by
physics_shape::scaled(). - PHYSICS_SHAPE_PLANE: a flat surface that is solid behind it, made by
physics_plane_shape_create().
Functions
boxes_intersect
Find out whether two rectangles on the x y plane, each of which may be rotated, overlap.
bool boxes_intersect(float minx1, float maxx1, float miny1, float maxy1, float r1, float minx2, float maxx2, float miny2, float maxy2, float r2);
Arguments:
- float minx1: the lowest x of the first rectangle.
- float maxx1: the highest x of the first rectangle.
- float miny1: the lowest y of the first rectangle.
- float maxy1: the highest y of the first rectangle.
- float r1: the rotation of the first rectangle in radians.
- float minx2: the lowest x of the second rectangle.
- float maxx2: the highest x of the second rectangle.
- float miny2: the lowest y of the second rectangle.
- float maxy2: the highest y of the second rectangle.
- float r2: the rotation of the second rectangle in radians.
Returns:
bool: true if the rectangles overlap, false otherwise.
physics_box_shape_create
Create a box shape.
physics_box_shape@ physics_box_shape_create(const vector&in half_extents, float convex_radius = 0.05f, physics_material@ mat = null);
Arguments:
const vector&in half_extents: half of the size of the box along each axis, so
vector(1, 2, 3)makes a box 2 meters wide, 4 deep and 6 tall.float convex_radius = 0.05f: how much the edges of the box are rounded, which makes collisions faster and more stable. The default is nearly always right, but must be smaller than the smallest half extent.
physics_material@ mat = null: the material of the shape, which gives bodies made from the shape their friction and restitution, and determines how it absorbs, scatters and lets through sound in acoustic simulations such as sound_environment, see
physics_material_get(). If null, the default material is used.
Returns:
physics_box_shape@: the new shape, or null if it could not be created, such as when a size is not positive.
Remarks:
Boxes are what you use for floors, walls, ceilings and crates, though physics_plane_shape_create() is simpler for a floor that goes on and on. A shape isn't a body, so it must be given to physics_world::create_and_add_body() before it does anything, and one shape can be used by any number of bodies.
Example:
void main() {
physics_world world;
physics_box_shape@ wall = physics_box_shape_create(vector(0.1, 5, 2), 0.05, physics_material_get("brick"));
world.create_and_add_body(wall, vector(0, 0, 2), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING);
alert("Bodies", "The world has " + world.num_bodies + " body.");
}
physics_capsule_shape_create
Create a capsule shape, a cylinder with a half sphere on each end.
physics_capsule_shape@ physics_capsule_shape_create(float half_height, float radius, physics_material@ mat = null);
Arguments:
- float half_height: half of the height of the straight part between the two ends, so the whole capsule is
2 * half_height + 2 * radiustall. - float radius: the radius of the capsule.
- physics_material@ mat = null: the material of the shape, which gives bodies made from the shape their friction and restitution, and determines how it absorbs, scatters and lets through sound in acoustic simulations such as sound_environment, see
physics_material_get(). If null, the default material is used.
Returns:
physics_capsule_shape@: the new shape, or null if it could not be created, such as when a size is not positive.
Remarks:
A capsule stands along the y axis of the shape, so to make one stand up in the world, where z is up, give its body a rotation of 90 degrees around the x axis such as quaternion_from_axis_angle(vector(1, 0, 0), 1.5707964). Capsules are a very good approximation of a standing person, since they slide smoothly along walls and up steps.
physics_cylinder_shape_create
Create a cylinder shape.
physics_cylinder_shape@ physics_cylinder_shape_create(float half_height, float radius, float convex_radius = 0.05f, physics_material@ mat = null);
Arguments:
- float half_height: half of the height of the cylinder.
- float radius: the radius of the cylinder.
- float convex_radius = 0.05f: how much the edges are rounded, see
physics_box_shape_create(). - physics_material@ mat = null: the material of the shape, which gives bodies made from the shape their friction and restitution, and determines how it absorbs, scatters and lets through sound in acoustic simulations such as sound_environment, see
physics_material_get(). If null, the default material is used.
Returns:
physics_cylinder_shape@: the new shape, or null if it could not be created, such as when a size is not positive.
Remarks:
Like a capsule, a cylinder stands along the y axis of the shape, so rotate its body to stand it up in a z up world. Cylinders suit barrels, pillars and wheels.
physics_material_get
Look up a material by name.
physics_material@ physics_material_get(const string&in name);
Arguments:
- const string&in name: the name of the material.
Returns:
physics_material@: the material, or null if no material has that name.
Remarks:
A physics_material describes a kind of surface. Bodies created from a shape that has a material start with the material's friction and restitution, and its acoustic properties control how sound is absorbed, scattered and let through it in acoustic simulations such as the nvgt_phonon plugin's sound_environment. Give one to a shape when you create it.
These materials are built in: generic, brick, concrete, ceramic, gravel, carpet, glass, plaster, wood, metal, rock, sand, snow, soil, foliage, water, drywall, marble, asphalt, grass, fabric, cardboard, plastic, rubber, foam and ice. physics_material_list() returns the names of every material that exists, including those you register yourself.
Example:
void main() {
physics_material@ wood = physics_material_get("wood");
if (wood is null) return;
alert("Wood", "Wood has a friction of " + wood.friction + " and a restitution of " + wood.restitution + ".");
}
physics_material_list
List the names of all known materials.
string[]@ physics_material_list();
Returns:
string[]@: the name of every material that physics_material_get() can find.
physics_plane_shape_create
Create a plane shape, a flat surface that is solid behind it and goes on as far as its half extent in every direction.
physics_plane_shape@ physics_plane_shape_create(const plane&in plane, float half_extent = 1000.0f, physics_material@ mat = null);
Arguments:
const plane&in plane: the surface of the shape, relative to the position of the body it is given to. Everything behind the plane, the side its normal points away from, is solid.
float half_extent = 1000.0f: how far the plane goes in every direction from the point on it that is closest to the shape's origin, so the default makes a plane 2 kilometers across, which is solid for 1 kilometer behind it. Keep this no bigger than the map needs, as a smaller plane is faster for the world to sort.
physics_material@ mat = null: the material of the shape, which gives bodies made from the shape their friction and restitution, and determines how it absorbs, scatters and lets through sound in acoustic simulations such as sound_environment, see
physics_material_get(). If null, the default material is used.
Returns:
physics_plane_shape@: the new shape, or null if it could not be created, such as when the plane's normal is zero or the half extent is not positive.
Remarks:
A plane is the simplest way to give a map a floor that nothing can fall through, no matter how fast it is going, as everything below the floor is solid rather than just a thin layer. It can also make the outer walls of a map, or a slope with a plane that is tilted.
Plane shapes can only be used for static and kinematic bodies, physics_world::create_and_add_body() fails if one is given with PHYSICS_BODY_DYNAMIC. Things that leave the area covered by the half extent no longer collide with the plane, and collisions right at its edge are unreliable, so make it a bit larger than the area that is walked on, and use a box for a floor of a particular size such as a platform.
Example:
void main() {
physics_world world;
physics_plane_shape@ ground = physics_plane_shape_create(plane(), 500, physics_material_get("grass"));
world.create_and_add_body(ground, vector(0, 0, 0), IDENTITY_QUATERNION, PHYSICS_BODY_STATIC, PHYSICS_LAYER_NON_MOVING);
physics_body_id ball = world.create_and_add_body(physics_sphere_shape_create(0.5), vector(0, 0, 10), IDENTITY_QUATERNION, PHYSICS_BODY_DYNAMIC);
for (int i = 0; i < 180; i++) world.update(1.0 / 60);
alert("Ball", "The ball has come to rest at " + world.get_position(ball));
}
physics_sphere_shape_create
Create a sphere shape.
physics_sphere_shape@ physics_sphere_shape_create(float radius, physics_material@ mat = null);
Arguments:
- float radius: the radius of the sphere in meters.
- physics_material@ mat = null: the material of the shape, which gives bodies made from the shape their friction and restitution, and determines how it absorbs, scatters and lets through sound in acoustic simulations such as sound_environment, see
physics_material_get(). If null, the default material is used.
Returns:
physics_sphere_shape@: the new shape, or null if it could not be created, such as when a size is not positive.
Remarks:
A sphere is the cheapest shape to simulate and rolls realistically, which makes it good for balls, grenades and other small projectiles.
physics_tapered_capsule_shape_create
Create a capsule shape whose two ends have different radii.
physics_tapered_capsule_shape@ physics_tapered_capsule_shape_create(float half_height, float top_radius, float bottom_radius, physics_material@ mat = null);
Arguments:
float half_height: half of the height of the tapered part between the centers of the two rounded ends. The whole shape is taller by both radii.
float top_radius: the radius of the end at the top (the positive y axis of the shape).
float bottom_radius: the radius of the end at the bottom (the negative y axis).
physics_material@ mat = null: the material of the shape, see
physics_material_get(). If null, the default material is used.
Returns:
physics_tapered_capsule_shape@: the new shape, or null if it could not be created, such as when a size is not positive.
Remarks:
The shape stands along the y axis of the shape, like a capsule, so rotate its body to stand it up in a z up world, see physics_capsule_shape_create(). A tapered capsule is shaped like a leg or a bowling pin, which is useful for characters that have a wide body and narrower head. The radii must be positive and the shape must be tall enough for the two ends not to swallow each other.
Example:
void main() {
physics_tapered_capsule_shape@ pin = physics_tapered_capsule_shape_create(0.5, 0.1, 0.25);
if (pin is null) return;
alert("Pin", "The shape has a volume of " + pin.volume + " cubic meters.");
}
physics_tapered_cylinder_shape_create
Create a cylinder shape whose two ends have different radii, a cone with the top cut off when one is small.
physics_tapered_cylinder_shape@ physics_tapered_cylinder_shape_create(float half_height, float top_radius, float bottom_radius, float convex_radius = 0.05f, physics_material@ mat = null);
Arguments:
- float half_height: half of the height of the shape.
- float top_radius: the radius of the flat end at the top (the positive y axis of the shape).
- float bottom_radius: the radius of the flat end at the bottom.
- float convex_radius = 0.05f: how much the edges are rounded, see
physics_box_shape_create(). It must not be larger than the smaller radius. - physics_material@ mat = null: the material of the shape, see
physics_material_get(). If null, the default material is used.
Returns:
physics_tapered_cylinder_shape@: the new shape, or null if it could not be created, such as when a size is not positive.
Remarks:
Like a cylinder, it stands along the y axis of the shape. Use it for shapes such as buckets, lamp shades and traffic cones.
rotate
Rotate a point around another on the x y plane.
vector@ rotate(const vector&in point, const vector&in origin, double theta, bool maintain_z = true);
Arguments:
- const vector&in point: the point to rotate.
- const vector&in origin: the point to rotate around.
- double theta: the angle to rotate by in radians, counterclockwise.
- bool maintain_z = true: whether to keep the point's z coordinate. If false, the result's z is 0.
Returns:
vector@: the rotated point.