LitDev Extension API

GW LD3DView LDArray LDBits LDBlueTooth
LDCall LDChart LDClient LDClipboard LDColours
LDCommPort LDController LDControls LDCursors LDDataBase
LDDateTime LDDebug LDDialogs LDDictionary LDEffect
LDEmail LDEncryption LDEvents LDFastArray LDFastShapes
LDFigures LDFile LDFinances LDFocus LDftp
LDGeography LDGraph LDGraphicsWindow LDHashTable LDHID
LDIcon LDImage LDInline LDIOWarrior LDList
LDLogic LDMath LDMathX LDMatrix LDMusic
LDNetwork LDPhysics LDProcess LDQueue LDRegex
LDResources LDScrollBars LDSearch LDServer LDSettings
LDShapes LDShell LDSort LDSound LDSpeech
LDStatistics LDStopwatch LDText LDTextWindow LDTimer
LDTranslate LDUnits LDUtilities LDVector LDWaveForm
LDWebCam LDWindows LDxml LDZip TW

LDPhysics
Physics extension using Box2D engine.

AddChain AddExplosion AddFixedAnchor
AddFixedShape AddInactiveShape AddMovingAnchor
AddMovingShape AddRope AttachShapes
AttachShapesWithJoint AttachShapesWithRotation BoxShape
BrakeTire ChainColour DetachJoint
DetachShapes DisconnectShape DoTimestep
FollowShapeX FollowShapeY GetAcceleration
GetAllShapesAt GetAngle GetCollisions
GetContacts GetInertia GetMass
GetPan GetPosition GetRotation
GetShapeAt GetTireInformation GetTireProperties
GetVelocity GroupShapes Help
LoadImagesAsCircles MaxPolygonVertices MaxProxies
MoveTire PanView PositionIterations
RayCast ReadJson RemoveChain
RemoveFrozen RemoveRope RemoveShape
Reset RopeColour Scaling
SetAABB SetAngle SetBoundaries
SetBullet SetDamping SetForce
SetGravity SetGroup SetImpulse
SetJointMotor SetPosition SetRotation
SetShapeGravity SetTire SetTireProperties
SetTorque SetVelocity TimeStep
TimestepControl ToggleMoving ToggleRotation
ToggleSensor TurnTire UngroupShapes
UnsetBullet VelocityIterations VelocityThreshold
WakeAll WriteJson

AddChain(shape1,shape2)
Add a chain between two existing shapes.
shape1 First shape.
shape2 Second shape.
returns The chain name.

AddExplosion(posX,posY,power,damping,colour)
Make an explosion, which consists of 50x20kg particles blast apart over 500ms.
posX The X coordinate of the explosion.
posY The Y coordinate of the explosion.
power The explosion force, this is the initial velocity of the blast particles.
damping A damping for the blast, the smaller this value the larger the blast range (default 10).
colour An optional colour of the explosion particles ("" for none).

AddFixedAnchor(posX,posY)
Add a new small, transparent shape to be used as a fixed anchor point.
posX The X coordinate of the anchor.
posY The Y coordinate of the anchor.
returns The anchor shape name.

AddFixedShape(shapeName,friction,restitution)
Add an existing SmallBasic shape to the physics engine as a fixed (non-dynamic) shape with friction and restitution that affects shapes that hit it.
shapeName The name of the shape.
friction The shape friction (usually 0 to 1).
restitution The shape restitution or bounciness (usually 0 to 1).
returns None.

AddInactiveShape(shapeName)
Add an existing SmallBasic shape to the physics engine as an inactive (non-dynamic and non-interacting) shape which only moves with the PanView method.
shapeName The name of the shape.
returns None.

AddMovingAnchor(posX,posY)
Add a new small, transparent and high density shape to be used as a moving anchor point.
posX The X coordinate of the anchor.
posY The Y coordinate of the anchor.
returns The anchor shape name.

AddMovingShape(shapeName,friction,restitution,density)
Add an existing SmallBasic shape to the physics engine as a moving (dynamic) shape.
shapeName The name of the shape.
friction The shape friction (usually 0 to 1).
restitution The shape restitution or bounciness (usually 0 to 1).
If a negative value is set for restitution, then the shape will be added with a very small size which may be used to add an inactive image that can be grouped within an irregular compound shape that matches the image boundary.

density The shape density (default 1).
returns None.

AddRope(shape1,shape2)
Add a rope between two existing shapes.
shape1 First shape.
shape2 Second shape.
returns The rope name.

AttachShapes(shape1,shape2)
Connect two shapes to move together as one. The shapes are connected with a distance joint and may wobble a bit if they are hit.
shape1 The first shape name.
shape2 The second shape name.
returns None.

AttachShapesWithJoint(shape1,shape2,type,collide,parameters)
Connect two shapes to move together as one with one of several joint types.
These can be advanced and require reference to Box2D manual.
In many cases it is best to prevent shape rotation for the joints to behave as desired.
Multiple joints may also be applied to shapes.
The methods use the initial shape positions, so set these first.

shape1 The first shape name.
shape2 The second shape name.
type One of the following joint types.

"Distance" - maintain a fixed distance between the shapes.
"Gear" - link Prismatic or Revolute joints (previously created) of 2 shapes.
"Line" - move the shapes along a line initially connecting the shapes.
"Mouse" - move the shape to follow the mouse (both shape names should be the same).
"Prismatic_H" - move shapes vertically along a line between the two shapes.
"Prismatic_V" - move shapes horizontally along a line between the two shapes.
"Pulley" - a pulley system, one shape moves up as the other moves down - position the shapes initially at the extreme points of the pulley motion.
"Revolute" - the shapes can rotate about each other.

collide The connected shapes can interact with each other "True" or "False" (default).
parameters Optional parameters (default ""), multiple parameters are in an array.

"Distance" - damping ratio (default 0)
"Gear" - gear ratio, first joint, second joint (default 1, auto detect joints)
"Line" - X direction, Y direction, lower translation, upper translation (default line connecting shapes, no limits)
"Mouse" - max acceleration, damping ratio (default 10000, 0.7)
"Prismatic_H" - X direction, Y direction, lower translation, upper translation (default 1,0, no limits)
"Prismatic_V" - X direction, Y direction, lower translation, upper translation (default 0,1, no limits)
"Pulley" - pulley ratio (block and tackle) (default 1)
"Revolute" - lower angle, upper angle (default no limits)

returns The joint name.

AttachShapesWithRotation(shape1,shape2)
Connect two shapes to move together as one, but allow the shapes to rotate about each other.
shape1 The first shape name.
shape2 The second shape name.
returns None.

BoxShape(shapeName,x1,y1,x2,y2)
Set a shape to remain within a box within the view.
This is similar to PanView, except that the view pans automatically to keep the specified shape within a box region of the GraphicsWindow.
Only one shape can be boxed. To unset shape box, set the shapeName to "".

shapeName The shape to box or "".
x1 The left x coordinate of the box.
y1 The top y coordinate of the box.
x2 The right x coordinate of the box.
y2 The bottom y coordinate of the box.

BrakeTire(shapeName)
Apply a brake to a tire shape.
shapeName The tire shape to brake.

ChainColour
The colour to be used for chains.

DetachJoint(jointName)
Disconnect two shapes that were previously joined with a joint.
jointName The joint name.
returns None.

DetachShapes(shape1,shape2)
Disconnect two shapes that were previously attached.
shape1 The first shape name.
shape2 The second shape name.
returns None.

DisconnectShape(shapeName)
Disconnect shape from the physics engine without deleting the shape.
shapeName The shape name.
returns None.

DoTimestep()
Perform a time-step update.
returns None.

FollowShapeX(shapeName)
Set a shape to remain stationary at X position in the view.
This is similar to PanView, except that the view pans automatically to keep the specified shape at a constant visual X location.
Only one shape can be followed in X direction. To unset shape following, set the shapeName to "".

shapeName The shape to follow or "".
returns None.

FollowShapeY(shapeName)
Set a shape to remain stationary at Y position in the view.
This is similar to PanView, except that the view pans automatically to keep the specified shape at a constant visual Y location.
Only one shape can be followed in Y direction. To unset shape following, set the shapeName to "".

shapeName The shape to follow or "".
returns None.

GetAcceleration(shapeName)
Get the acceleration of the shape.
shapeName The shape name.
returns A 2 element array with the shape acceleration.

GetAllShapesAt(posX,posY)
Get an array of all the physics engine shapes (if any) at the input coordinates.
The coordinates for this method are the physics engine coordinates if panning is present.

posX The X coordinate.
posY The Y coordinate.
returns An array of shape names or "".

GetAngle(shapeName)
Get the angle of rotation for the shape.
shapeName The shape name.
returns The angle of rotation in degrees.

GetCollisions(shapeName)
Get an array of all the shapes that the specified shape collided with during the last DoTimestep().
shapeName The shape to check for collisions.
returns An array of all the shapes collided with (may be empty "" or "Wall" for a static obstacle).

GetContacts(posX,posY,distance)
Get a list of shapes that collided within a distance of a specified contact point.
posX The X coordinate of a contact position to check.
posY The Y coordinate of a contact position to check.
distance A maximum distance from the contact point for the contact.
returns An array of contacts, with each contact being an array of 2 shape names.

GetInertia(shapeName)
Get the moment of inertia of a shape.
shapeName The shape name.
returns The inertia of the shape.

GetMass(shapeName)
Get the mass of a shape.
shapeName The shape name.
returns The mass of the shape.

GetPan()
Get the current pan offset, see PanView, FollowShapeX(Y) and BoxShape.
World coordinates = screen coordinates + pan offset.

returns A 2 element array with the current pan offset.

GetPosition(shapeName)
Get the centre of the shape coordinates.
shapeName The shape name.
returns A 2 element array with the shape centre position.

GetRotation(shapeName)
Get the shape rotation speed.
shapeName The shape name.
returns The angular rotation speed degrees/s.

GetShapeAt(posX,posY)
Get the shape (if any) at the input coordinates.
The coordinates for this method are the screen coordinates if panning is present.

posX The X coordinate.
posY The Y coordinate.
returns The shape name at the input position or "".

GetTireInformation(shapeName)
Get tire information, it includes:

Skid (if this value exceeds the property AntiSkid, then the tire is skidding)
Crash (the value is the speed of the impact)

shapeName The tire shape.
returns An array of information, indexed by the information name, e.g. "Skid".

GetTireProperties(shapeName)
Get tire properties, they include:

AntiSkid (higher value reduces skid)
Drag (higher value increases forward/backward drag)
Brake (higher value increases braking power)
Straighten (higher value restores steering more quickly)
BrakeStraighten (higher value restores steering more quickly while braking)

shapeName The tire shape.
returns An array of properties, indexed by the property name, e.g. "AntiSkid".

GetVelocity(shapeName)
Get the velocity of the shape.
shapeName The shape name.
returns A 2 element array with the shape velocity.

GroupShapes(shape1,shape2)
Solidly group two shapes to move together as one. Shape1 is added to shape2 to act as one shape.
shape1 The first shape name.
shape2 The second shape name.
returns None.

Help()
This function is just to display this help.

The extension uses Box2D (http://box2d.org) as an engine and provides an interface between it and the graphics capabilities of SmallBasic.

Only shapes that are connected to the physics engine take part in the motion physics, for example you may add normal shapes (e.g. a gun and not connect it to the physics engine). Once a shape is connected to the engine, it is best to only interact with it through the methods provided by the extension. All positions are in the SmallBasic GraphicsWindow pixels and refer to shape centres.

Image and text shapes are treated as rectangles, and ellipses as circles; there is also triangle and convex polygon support, but not lines. Images may be treated as circles by setting the property LoadImagesAsCircles to "True".

One issue that Box2D has difficulty with is small fast moving objects that can 'tunnel' through other shapes without being deflected (see the SetBullet option).

Another problem is shapes of very different size and hence mass, especially large shapes when they are connected together. It may be necessary to modify the density for these (the Anchor options are an attempt to automate this a bit), otherwise the default density of 1 is good. Resist the temptation to connect too many shapes together.

It may be possible to improve the stability of some 'difficult' models using the TimestepControl settings, but the defaults look good for most cases.

Do not call the physics methods inside SmallBasic event subroutines directly, rather set flags that can be processed in a main game loop.

There are sample SmallBasic programs and a Getting Started Guide that comes with the extension dll - this is the best place to start.

Report bugs and problems to the SmallBasic forum (http://social.msdn.microsoft.com/Forums/en-US/smallbasic/threads), but first simplify your SmallBasic code to isolate the issue before providing a short 'runnable' code sample.

returns None.

LoadImagesAsCircles
Toggle whether image shapes will be loaded as circles - "True" or "False" (default is "False").

MaxPolygonVertices
The physics engine maximum number of vertices on convex polygons (default 8).

MaxProxies
The physics engine maximum number of objects 'proxies' (default 1024).

MoveTire(shapeName,force)
Move a tire shape, apply a forward or backward force.
shapeName The tire shape to move.
force The force to apply, positive is forward, negative is backward.

PanView(panHorizontal,panVertical)
Pan the camera view, including window boundaries.
panHorizontal Pan in the horizontal direction (negative is left).
panVertical Pan in the vertical direction (negative is up).
returns None.

PositionIterations
The physics engine position iterations (default 2).

RayCast(shapeName,angle,distance)
Cast an invisible ray to detect the proximity of shapes.
shapeName The shape to cast the ray from.
angle The angle in degrees to check, this can also be an array of angles.
distance A maximum distance to check.
returns An array of results, indexed by the shape name ("Wall" for a static obstacle) with a value equal to its distance.
The shapes are sorted to list them nearest first.
If an array of input angles is used, then only the nearest shape for each angle is returned and the value is the angle, not the distance.


ReadJson(fileName,scale,reverseY,stationary,offsetX,offsetY)
Read in a json script compatible with R.U.B.E. and create a LDPhysics model.
See https://www.iforce2d.net/rube for more details.

fileName The full path to the json file to read.
scale Scale all shapes, default 1 (no scaling).
reverseY Reverse the Y direction up to down ("True" or "False").
stationary Set all shapes to be initially at rest, joint motors are still enabled ("True" or "False").
offsetX Add an x coordinate offset to all shapes.
offsetY Add a y coordinate offset to all shapes, especially useful when reverseY is set.
returns A text array containing the LDPhysics commands used to create the model.

RemoveChain(shapeName)
Remove a chain.
shapeName The chain name.
returns None.

RemoveFrozen()
Removes all frozen shapes - outside the AABB for the engine.
returns None.

RemoveRope(shapeName)
Remove a rope.
shapeName The rope name.
returns None.

RemoveShape(shapeName)
Remove a shape.
shapeName The name of the shape.
returns None.

Reset()
Reset (delete all physics engine attached shapes).
returns None.

RopeColour
The colour to be used for ropes.

Scaling
The physics engine scaling (pixel/m, default 10). It is not recommended to change this.

SetAABB(minX,maxX,minY,maxY)
The physics engine AABB (axis-aligned bounding box). The units are the engine units of m. A Reset is required after setting. It is not recommended to change this.
minX The left coordinate of the universe (default -100).
maxX The right coordinate of the universe (default 300).
minY The top coordinate of the universe (default -100).
maxY The bottom coordinate of the universe (default 300).
returns None.

SetAngle(shapeName,angle)
Reset the angle of rotation for a shape.
shapeName The shape name.
angle The angle of rotation in degrees.
returns None.

SetBoundaries(left,right,top,bottom)
Set solid boundaries (positioning a boundary outside the GraphicsWindow removes it).
left The left boundary X value.
right The right boundary X value.
top The top boundary Y value.
bottom The bottom (ground) boundary Y value.
returns None.

SetBullet(shapeName)
Set a shape as a bullet. This prevents 'tunnelling' of fast moving small objects at the expense of performance.
shapeName The shape name.
returns None.

SetDamping(shapeName,linear,angular)
Set a damping factor for a shape (default 0).
shapeName The shape to modify.
linear Linear damping factor.
angular Angular damping factor.
returns None.

SetForce(shapeName,forceX,forceY)
Set a force to apply to a shape (Remember F = ma).
shapeName The shape to modify.
forceX X component of the force.
forceY Y component of the force.
returns None.

SetGravity(gravX,gravY)
Set the gravity direction and magnitude (default 0,100).
gravX The X component of gravity.
gravY The Y component of gravity.
returns None.

SetGroup(shapeName,group,mask)
Control which sprites interact (collide) with other shapes.
shapeName The shape to modify.
group The group that the current shape belongs to (default 0). This should be an integer between 0 and 15.
mask An array of groups that this shape will collide with (default all groups 0,1,2,..,14,15).
To allow the shape to only interact with groups 0, 1 and 4 would be "1=0;2=1;3=4;".

returns None.

SetImpulse(shapeName,impulseX,impulseY)
Set an impulse to a shape (a kick).
shapeName The shape to modify.
impulseX X component of the impulse.
impulseY Y component of the impulse.
returns None.

SetJointMotor(jointName,speed,maxForce)
Set a motor for selected joints (Line, Prismatic_H, Prismatic_V and Revolute).
jointName The joint name.
speed The desired motor speed.
maxForce The maximum motor force (torque for Revolute).
A zero value turns motor off.


SetPosition(shapeName,posX,posY,angle)
Reset shape position.
shapeName The shape to modify.
posX X component shape centre.
posY Y component shape centre.
angle The angle of rotation in degrees.
returns None.

SetRotation(shapeName,rotation)
Set shape rotation speed.
shapeName The shape to modify.
rotation The angular rotation speed degrees/s.
returns None.

SetShapeGravity(shapeName,gravX,gravY)
Set the gravity direction and magnitude for an individual shape (default 0,100).
shapeName The shape to modify.
gravX The X component of gravity.
gravY The Y component of gravity.
returns None.

SetTire(shapeName)
Set an object to act as a drivable tire for a top down game.
Usually gravity will be 0 and the shape should already be added to the engine.
The object should be initially positioned facing forward up on the display.

shapeName The shape to make a tire.

SetTireProperties(shapeName,properties)
Set tire properties, they include:

AntiSkid (higher value reduces skid)
Drag (higher value increases forward/backward drag)
Brake (higher value increases braking power)
Straighten (higher value restores stearing more quickly)
BrakeStraighten (higher value restores stearing more quickly while braking)

shapeName The tire shape.
properties An array of one or more properties to set.
The index is one of the properties (case sensitive) and the value is the property value.


SetTorque(shapeName,torque)
Set a torque to a shape (a rotational kick).
shapeName The shape to modify.
torque The torque to apply.
returns None.

SetVelocity(shapeName,velX,velY)
Set the velocity of a shape.
shapeName The shape to modify.
velX X component of the velocity.
velY Y component of the velocity.
returns None.

TimeStep
The physics engine timestep size (default 0.025).

TimestepControl(timestep,velocityIterations,positionIterations)
Modify default timestep control parameters - also can be set using individual parameters.
timestep Time-step (default 0.025).
velocityIterations Velocity iterations (default 6).
positionIterations Position iterations (default 2).
returns None.

ToggleMoving(shapeName)
Toggle a moving shape to be fixed and vice-versa.
This method also sets the rotation to be on or off to match if it is moving or fixed.

shapeName The shape name.

ToggleRotation(shapeName)
Toggle a shape to not rotate and vice-versa.
This method toggles the rotation property for fixed and moving shapes.

shapeName The shape name.

ToggleSensor(shapeName)
Toggle a shape to act as a sensor and vice-versa.
A sensor shape does not interact with other shapes, but still provides collision data.

shapeName The shape name.

TurnTire(shapeName,torque)
Turn a tire shape, steer left or right.
shapeName The tire shape to turn.
torque The torque, rotation force to apply, positive is turn right, negative is turn left.

UngroupShapes(shape1,shape2)
Remove shape group pairing.
shape1 The first shape name.
shape2 The second shape name.
returns None.

UnsetBullet(shapeName)
Unset a shape as a bullet. This reverts the shape to normal collision detection.
shapeName The shape name.
returns None.

VelocityIterations
The physics engine velocity iterations (default 6).

VelocityThreshold
The physics engine velocity threshold for inelastic collisions 'sticky walls' (default 1).

WakeAll()
Wake all sleeping shapes - shapes sleep due to no applied forces or contacts. They wake automatically on any contact or applied force, so this action is rarely required.
returns None.

WriteJson(fileName)
Write out a json script compatible with R.U.B.E. from current LDPhysics model.
See https://www.iforce2d.net/rube for more details.

fileName The full path to the json file to create.