Physics-GettingStartedGuide For Small Basic
Physics-GettingStartedGuide For Small Basic
Summary Overview
This extension uses Box2D (http://box2d.org) as an engine and provides an interface between it
and the graphics capabilities of Small Basic.
An older C# port of Box2D and not the current main feature release (C++) version was used for
various technical compatibility reasons, namely earlier versions of Small Basic that targeted .Net
3.5 SP1 and AnyCPU platform. However, the port being used for this extension behaves well,
with only small modifications.
Image shapes can be treated as circles by setting the property LoadImagesAsCircles to "True"
before loading the images. Also, the Controls objects TextBox and Button can be used, and are
treated as rectangles.
Additionally, the FC (or other) extension shapes and controls can be used and are treated by
default as rectangles. An exception is the FCControls.AddPolygon or LDShapes.AddPolygon
which creates a polygon that is also supported by this extension as long as the polygon is convex.
Page 1
Create the shape using one of the Small Basic Shapes.Add methods.
Position the shape using Shapes.Move.
Add the shape to the physics engine using one of the LDPhysics.Add methods.
Create the shape using one of the Small Basic Shapes.Add methods.
Add the shape to the physics engine using one of the LDPhysics.Add methods.
Position the shape centre using LDPhysics.SetPosition.
Physical Properties
Gravity is set to be vertically down on the screen.
Solid borders, where all shapes will bounce, are initially set on all sides of the GraphicsWindow.
These can be altered using the LDPhysics.SetBoundaries method.
Any shape or body in the engine will have numerous properties; here is a list of the main ones
that this extension can interact with.
Body Property
Time
Pixel
Position
Angle
Velocity
Rotation
Impulse
Force
Torque
Friction
Restitution
Density
Comment
The time interval used is the second, the default time-step is 0.025 or 40th of
a second
Equivalent to 0.1m
The centre of the body in Small Basic coordinates (pixels).
The angle of rotation (degrees)
Linear velocity at the body centre (pixel/s)
The rotation speed of the body (degrees/s)
An instantaneous kick that may be applied to a body (mass.pixel/s)
A force (mass times acceleration) applied to a body (mass.pixel/s2)
A rotational force (inertia * rotational acceleration) that may be applied to a
body (mass.pixel2/s2)
Slowing of the body when it rolls or slides over another body (0 to 1 or larger)
The bounciness of the body when it collides with another (0 to 1)
The density of the body (default 1 good for most cases) (kg/m2 or
0.01kg/pixel2)
Page 2
The game loop concept is common to all dynamic interaction type software and worth using
from the start.
Other game-play interactions are made inside this game loop, such as moving barriers, firing
bullets, adding or removing bodies etc.
Page 3
Additional Comments
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 Small Basic GraphicsWindow pixels and refer
to shape centres.
Stacking heavy bodies on top of much lighter bodies is not stable. Stability degrades as the mass
ratio passes 10:1.
Chains of bodies connected by joints may stretch if a lighter body is supporting a heavier body.
o For example, a wrecking ball connected to a chain of light weight bodies may not be stable.
o Stability degrades as the mass ratio passes 10:1.
There is typically around 0.5cm of slop in shape versus shape collision.
Continuous collision does not handle joints. So you may see joint stretching on fast moving objects.
It may be possible to improve the stability of some 'difficult' models using the TimestepControl
settings, but the defaults look good for most cases. It is often better to consider reducing mass
and size variation between shapes. Again, Erin states:
Box2D uses a computational algorithm called an integrator. Integrators simulate the physics
equations at discrete points of time. This goes along with the traditional game loop where we
essentially have a flip book of movement on the screen. So we need to pick a time step for Box2D.
Generally physics engines for games like a time step at least as fast as 60Hz or 1/60 seconds. You
can get away with larger time steps, but you will have to be more careful about setting up the
definitions for your world. We also don't like the time step to change much. A variable time step
produces variable results, which makes it difficult to debug. So don't tie the time step to your
frame rate (unless you really, really have to).
In addition to the integrator, Box2D also uses a larger bit of code called a constraint solver. The
constraint solver solves all the constraints in the simulation, one at a time. A single constraint can
be solved perfectly. However, when we solve one constraint, we slightly disrupt other constraints.
To get a good solution, we need to iterate over all constraints a number of times.
There are two phases in the constraint solver: a velocity phase and a position phase. In the
velocity phase the solver computes the impulses necessary for the bodies to move correctly. In the
Page 4
Fixture Types
There are several ways a Small Basic shape may be added to the physics engine. The shapes may
move or not (anchors), rotate or not or even have some special characteristics. Some of these
behaviours may be modified after the shape is added.
Below are a set of tables listing the LDPhysics methods by group with some basic comments.
Page 5
Fixture
Modifiers
Bullet
Tire
Change Type
Methods
AddFixedAnchor
AddMovingAnchor
AddFixedShape
AddMovingShape
AddInactiveShape
Methods
Visible
x
x
x
Interacts
x
x
x
x
Can Move
Can Rotate
Comments
AddChain
Connects a chain between 2 existing shapes
RemoveChain
ChainColour
AddRope
Connects a rope between 2 existing shapes
RemoveRope
RopeColour
AddExplosion Temporarily add a large number of invisible shapes moving fast
away from explosion center
Methods
Comments
SetBullet
UnsetBullet
SetTire
MoveTire
TurnTire
BrakeTire
GetTireProperties
SetTireProperties
GetTireInformation
ToggleMoving
ToggleRotation
ToggleSensor
Fixture Removal
Remove
Disconnect
Frozen
Methods
RemoveShape
DisconnectShape
RemoveFrozen
Fixture
Connections
Attach
Methods
Comments
AttachShapes
AttachShapesWithRotation
DetachShapes
GroupShapes
UngroupShapes
AttachShapesWithJoint
SetJointMotor
DetachJoint
Group
Joints
Comments
Remove a shape completely
Remove a shape from interacting, while leaving it visible
Remove shapes outside the interaction region AABB
Page 6
Fixture Control
Get Properties
Setup Properties
Simulation
Properties
Sleeping
World
Creation
Remove
Gravity
Timestep
Fixtures
Control
Methods
GetAllShapesAt
GetAngle
GetCollisions
GetContacts
GetInertia
GetMass
GetPosition
GetRotation
GetShapeAt
GetVelocity
RayCast
SetAngle
SetDamping
SetGroup
SetPosition
SetRotation
SetVelocity
SetForce
SetImpulse
SetTorque
WakeAll
Methods
SetAABB
SetBoundaries
Scaling
Help
ReadJson
WriteJson
Reset
SetGravity
SetShapeGravity
TimeStep
TimestepControl
PositionIterations
VelocityIterations
VelocityThreshold
DoTimestep
LoadImagesAsCircles
MaxPolygonVertices
MaxProxies
PanView
FollowShapeX
FollowShapeY
BoxShape
GetPan
Comments
Get shape properties
Page 7
Note on Units
Since this is a physics extension I have made some effort to honour the rigor in Box2D and stick to
consistent units so that position, velocity, acceleration and rotation are consistent with the mass,
inertia and applied forces and torques in the Small Basic units.
This keeps the physics right, but the units can be ignored and just use values for force and torque
etc. that work in the context of your model.
The underlying Box2D units are not appropriate to the pixel units used in Small Basic, so a
conversion factor 10 (pixels/m) was applied, while maintaining the Box2D time unit of seconds. 1
pixel corresponds to 0.1m in Box2D internal units. Therefore the unit of acceleration due to
gravity (10m/s2) is 100 pixel/s2.
To use the Force, Impulse and Torque it is easiest to use the Mass and Moment of Inertia that can
be obtained for shapes.
Density is set to be in units of kg/m2. Thus, a square shape with sides 10 * 10 pixels will have
area of 100 pixel2 and therefore internal area of 1 m2 and therefore a mass of 1 kg using the
default density of 1 kg/m2.
Therefore:
LDPhysics.SetForce(shape,0,-LDPhysics.GetMass(shape))
LDPhysics.SetImpulse(shape,0,-LDPhysics.GetMass(shape)/LDPhysics.TimeStep)
Either of the above commands will accelerate the shape upwards at a rate of 1 pixel/s2.
LDPhysics.SetTorque(shape,LDPhysics.GetInertia(shape))
The above command will apply a rotational acceleration to the shape clockwise at a rate of 1
radian/s2 (about 57 degrees/s2). I have stuck to radian/s2, rather than degree/s2 since there are
physical relationships between applied forces, torques and power that I want to maintain.
Page 8
The other files in this extension zip include documentation, the examples used in the
documentation and some other Small Basic samples. These files are not required for the
extension to work and should not be saved in the lib folder, perhaps put them in your Documents
folder.
Page 9
Examples
The following is a set of examples that briefly demonstrates the main features of this extension,
with an emphasis on how to get the engine to achieve convincing physical simulations.
They are just a beginning; the limits depend mainly on imagination and ingenuity, and perhaps
performance, when you should be moving beyond Small Basic.
Something that looks convincing may be completely physically wrong; it just looks plausible
great for games, but perhaps not for weather forecasting or engineering simulators. Since this is
about simulating physics I add the warning not to believe any simulation (not specifically Box2D
but any computer simulation) has any bearing on reality, regardless of how realistic and
impressive the graphics look in fact I would suggest the more effort has been spent making it
look visually realistic the less realistic the simulation is likely to be.
The main steps for any dynamic visual (game) program are the same, also for Small Basic and
especially using this extension are:
Page 10
Set its initial position near the top of the window with zero rotation (irrelivant for a circle) if we
dont set its position in the engine it will take the current position of the shape.
LDPhysics.SetPosition(ball,200,100,0)
Page 11
Add a fixed anchor point 200 pixels to the right of the block and attach a rope between the fixed
anchor and the block.
anchor = LDPhysics.AddFixedAnchor(400,100)
LDPhysics.AddRope(anchor,block)
Page 12
To hang from a position that is not at the centre of a shape we need to create an anchor on the
corner of the block and attach the anchor to the block and the chain.
Create the objects in Small Basic
We only need the block shape, since the chain method is special to the physics engine.
block = Shapes.AddRectangle(50,50)
Add a moving anchor positioning it on one of the corners of the block and then attach it to the
block.
anchor1 = LDPhysics.AddMovingAnchor(225,125)
LDPhysics.AttachShapes(anchor1,block)
Add a fixed anchor point 200 pixels to the right of the block and attach a chain between the fixed
anchor and the anchor on the block.
anchor2 = LDPhysics.AddFixedAnchor(400,100)
LDPhysics.AddChain(anchor1,anchor2)
Page 13
Page 14
Create the objects in Small Basic and attach to the physics engine
Create 20 blocks and stack them up from the bottom of the window. We dont really need to put
the created blocks in an array unless we want to access them individually later.
For i = 1 To 20
block[i] = Shapes.AddRectangle(20,20)
LDPhysics.AddMovingShape(block[i],0.3,0.8,1)
LDPhysics.SetPosition(block[i],500,GraphicsWindow.Height-20*i+10,0)
EndFor
Create a small bullet and position it at the left of the screen and give it a large positive initial
velocity. We could give it more mass using a larger density or set it as a bullet type body using
LDPhysics.SetBullet, but here it seems OK as it is.
bullet = Shapes.AddEllipse(8,8)
LDPhysics.AddMovingShape(bullet,0,1,1)
LDPhysics.SetPosition(bullet,50,200,0)
LDPhysics.SetVelocity(bullet,1000,0)
Page 15
Page 16
Page 17
Tell the physics engine that the image shapes are to be circles.
LDPhysics.LoadImagesAsCircles = "True"
Create the Small Basic image shapes, add them to the physics engine, set their position randomly,
and also set a random initial velocity.
For i = 1 To 10
ball = Shapes.AddImage(image)
LDPhysics.AddMovingShape(ball,0.2,0.9,1)
LDPhysics.SetPosition(ball,Math.GetRandomNumber(500),Math.GetRandomNumber(300),0)
LDPhysics.SetVelocity(ball,Math.GetRandomNumber(51)-101,0)
EndFor
Page 18
Attach the car body to the physics engine as a moving shape and position it.
LDPhysics.AddMovingShape(car,0.3,0.5,1)
LDPhysics.SetPosition(car,250,360,0)
Page 19
Page 20
Following example 7, we create the car, use images for wheels that are set to be circles in the
physics engine.
Create the objects in Small Basic and attach to the physics engine
The wheels have a high friction value of 10 to reduce wheel spin.
image = ImageList.LoadImage(Program.Directory+"/gear_wheel.png")
wheel1 = Shapes.AddImage(image)
wheel2 = Shapes.AddImage(image)
car = Shapes.AddRectangle(200,20)
LDPhysics.LoadImagesAsCircles = "True"
LDPhysics.AddMovingShape(wheel1,10,0,1)
LDPhysics.AddMovingShape(wheel2,10,0,1)
LDPhysics.SetPosition(wheel1,180,400,0)
LDPhysics.SetPosition(wheel2,320,400,0)
LDPhysics.AddMovingShape(car,0.3,0.5,1)
LDPhysics.SetPosition(car,250,380,0)
LDPhysics.AttachShapesWithRotation(wheel1,car)
LDPhysics.AttachShapesWithRotation(wheel2,car)
LDPhysics.SetVelocity(car,100,0)
Page 21
Page 22
left = 0
right = 0
GraphicsWindow.KeyDown = OnKeyDown
GraphicsWindow.KeyUp = OnKeyUp
mass = LDPhysics.GetMass(car)
inerta = LDPhysics.GetInertia(wheel1)
While ("True")
If (left = 1) Then
LDPhysics.SetTorque(wheel1,-50*inerta)
LDPhysics.SetTorque(wheel2,-50*inerta)
LDPhysics.SetImpulse(car,-mass,-0.1*mass)
EndIf
If (right = 1) Then
LDPhysics.SetTorque(wheel1,50*inerta)
LDPhysics.SetTorque(wheel2,50*inerta)
LDPhysics.SetImpulse(car,mass,-0.1*mass)
EndIf
LDPhysics.DoTimestep()
Program.Delay(20)
EndWhile
Sub OnKeyDown
k = GraphicsWindow.LastKey
If (k = "Left") Then
left = 1
EndIf
If (k = "Right") Then
right = 1
EndIf
EndSub
Sub OnKeyUp
k = GraphicsWindow.LastKey
If (k = "Left") Then
left = 0
EndIf
If (k = "Right") Then
right = 0
EndIf
EndSub
Page 23
We use example 4 as a starting point and modify it to change the colour of any block hit by the
bullet.
Modify the game loop
We use the LDPhysics.GetCollisions method to get a list of blocks hit by the bullet and change
their colour using the LDShapes.BrushColour method.
While ("True")
LDPhysics.DoTimestep()
hits = LDPhysics.GetCollisions(bullet)
For i = 1 To Array.GetItemCount(hits)
If (hits[i] <> "Wall") Then
LDShapes.BrushColour(hits[i],"Red")
EndIf
EndFor
Program.Delay(20)
EndWhile
Page 24
Example 10 A balloon with a suspended rope and box (Mass and Forces)
Page 25
Page 26
Demo showing rectangle, circle and triangle shapes; triangles were a struggle to integrate with
Small Basic due to the way they move and rotate try moving or rotating a triangle in Small Basic
and figure out what it is doing.
The whole thing
GraphicsWindow.PenWidth = 1
For i = 1 To 50
mode = Math.GetRandomNumber(3)
If (mode = 1) Then
GraphicsWindow.BrushColor = "Yellow"
temp = Shapes.AddRectangle(20+Math.GetRandomNumber(20),20+Math.GetRandomNumber(20))
LDPhysics.AddMovingShape(temp,0.5,0.8,1)
LDPhysics.SetPosition(temp,Math.GetRandomNumber(600),50,0)
ElseIf (mode = 2) Then
GraphicsWindow.BrushColor = "Red"
rad = 20+Math.GetRandomNumber(20)
temp = Shapes.AddEllipse(rad,rad)
LDPhysics.AddMovingShape(temp,0.5,0.8,1)
LDPhysics.SetPosition(temp,Math.GetRandomNumber(600),50,0)
Else
GraphicsWindow.BrushColor = "Green"
temp = Shapes.AddTriangle(0,0,20+Math.GetRandomNumber(20),0,0,2+Math.GetRandomNumber(20))
LDPhysics.AddMovingShape(temp,0.5,0.8,1)
LDPhysics.SetPosition(temp,Math.GetRandomNumber(600),50,0)
EndIf
EndFor
While ("True")
LDPhysics.DoTimestep()
Program.Delay(20)
EndWhile
Page 27
Two ways to attach shapes are available, AttachShapes and GroupShapes. The attach method
works best for objects with moving parts, for example car wheels, but the attached shapes can
move a bit when they collide with other shapes or boundaries they are springy. The group
method maintains completely rigid connections.
As well as, and probably a consequence of being springy, the attached shapes appear to slowly
consume linear and rotational momentum, while the grouped shapes appear to slowly gain
momentum.
A compound body is any collection of attached or grouped shapes.
The only problems when mixing attached and grouped shapes in the same compound body seem
to be when the shapes have very different masses, which can be fixed by using appropriate
densities.
In the terminology of Box2D, attached shapes are connected by Revolute and Distance joints,
while grouping moves the shapes into one body.
Therefore using the grouping method, the position, velocity and angle for all grouped shapes will
be the same since they are now the same body. The position of the compound body (SetPosition
and GetPosition) refers to that of the second shape entered using the GroupShapes command
(the first shape is added into the second, maintaining their relative positions). The centre of
mass and hence the centre of rotation is recalculated for the grouped compound body and will in
general be different from its position (that of the shape to which others are grouped). This also
means that the mass, inertia, force, torque etc. for any shape in the group now applies to the
compound body as a whole. The collisions reported using GetCollisions still refer to the original
shapes.
The recommended approach is:
Use the AttachShapes method for any compound body that will have internal movement such as
rotation, connected rope/chain etc.
Use the GroupShapes method for a compound body which has no moving parts, but is just a
collection of shapes.
It is possible to attach and group shapes into complex bodies, but some care has to be taken to
create a stable model. First group all shapes as required into compound bodies, then to attach
(usually with rotation) these compound bodies.
Page 28
Page 29
If we dont interact with the physics engine, the shapes will fall, roll or swing etc. depending on
what they are. If we want a paddle or other user movable object to interact with the moving
shapes, then we cannot just move it since this will be seen like teleporting by the physics engine
the shape just disappeared from one place and reappeared in another. If this happens any
interactions during the implied movement are lost.
The following is one approach to handling this and has a few steps.
Create the user moving shape with a very large density (therefore large mass) and therefore wont
move much when hit by other moving bodies.
Apply a vertically up force to counteract gravity the only remaining forces on the shape that can
cause movement will be collisions from other shapes, but since they are light compared to our
shape, these movements will be small.
We can then reposition our shape to account for any small movements if we want it to be
stationary a teleport, but a very small one.
We can then apply additional forces or torques to move or rotate our shape as required. It is
important to apply a force or torque and not just reposition or rotate our shape manually if we
want it to interact with the environment.
Page 30
An alternative method
The following is an alternative approach, attaching the paddle with rotation to a fixed central
anchor.
gw = 600
gh = 600
GraphicsWindow.Width = gw
GraphicsWindow.Height = gh
'Very heavy thin paddle, just smaller than the window
GraphicsWindow.PenWidth = 0
GraphicsWindow.BrushColor = "Black"
rod = Shapes.AddRectangle(gw-2,2)
LDPhysics.AddMovingShape(rod,0.3,0.5,1000000)
LDPhysics.SetPosition(rod,gw/2,gh/2,0)
'Attach with rotation to a fixed anchor
anchor = LDPhysics.AddFixedAnchor(gw/2,gh/2)
LDPhysics.AttachShapesWithRotation(anchor,rod)
'Some blocks
GraphicsWindow.PenWidth = 1
GraphicsWindow.BrushColor = "Yellow"
For i = 1 To 20
block = Shapes.AddRectangle(20,20)
LDPhysics.AddMovingShape(block,0.3,0.9,1)
LDPhysics.SetPosition(block,gw/2,gh-i*20,0)
LDPhysics.SetBullet(block)
EndFor
LDPhysics.TimeStep = 0.01 '100 fps
Page 31
Page 32
We then need to act on this flag in the main game loop. We use the method GetShapeAt, which
returns the shape (if any) at the input coordinates in this case the mouse coordinates.
If (mouseDown = 1) Then
xM = GraphicsWindow.MouseX
yM = GraphicsWindow.MouseY
hit = LDPhysics.GetShapeAt(xM,yM)
If (hit <> "") Then
LDPhysics.SetImpulse(hit,0,-1000*LDPhysics.GetMass(hit))
EndIf
mouseDown = 0
EndIf
Page 33
Sub OnMouseDown
mouseDown = 1
EndSub
Page 34
Using the FC or LDShapes extension, it is possible to create and use general polygons, and as long
as they are convex (all internal angles are less than 180 degrees) they can also be used by this
extension. As an alternative it is possible to create compound shapes using the GroupShapes
method, which is required in any case for shapes with concave boundaries or compound objects
with varying properties such as density or restitution.
The whole thing
points[0]["X"]
points[0]["Y"]
points[1]["X"]
points[1]["Y"]
points[2]["X"]
points[2]["Y"]
points[3]["X"]
points[3]["Y"]
points[4]["X"]
points[4]["Y"]
=
=
=
=
=
=
=
=
=
=
0
0
40
0
60
40
40
80
0
20
For i = 1 To 10
polygon = LDShapes.AddPolygon(points)
LDPhysics.AddMovingShape(polygon,0.5,0.8,1)
LDPhysics.SetPosition(polygon,60*i,100,0)
LDPhysics.SetTorque(polygon,100*LDPhysics.GetInertia(polygon))
EndFor
While ("True")
LDPhysics.DoTimestep()
Program.Delay(20)
EndWhile
Page 35
If we want to increase the off-screen region where the physics calculations are performed we
could set the AABB at the start of the code (the first Physics command). The following sets the X
(horizontal) region to 1000 m or 10000 pixels using the default scaling of 10 pixel/m.
LDPhysics.SetAABB(-1000,1000,-100,200)
LDPhysics.Reset()
We write a subroutine to pan the display (10 pixels per step) when the key-press flag is set.
Sub handleEvents
speed = 10
If (panLeft = 1) Then
LDPhysics.PanView(-speed,0)
EndIf
If (panRight = 1) Then
LDPhysics.PanView(speed,0)
EndIf
EndSub
Page 36
For i = 1 To 50
mode = Math.GetRandomNumber(3)
If (mode = 1) Then
GraphicsWindow.BrushColor = "Yellow"
temp = Shapes.AddRectangle(20+Math.GetRandomNumber(20),20+Math.GetRandomNumber(20))
LDPhysics.AddMovingShape(temp,0.5,0.8,1)
LDPhysics.SetPosition(temp,Math.GetRandomNumber(600),50,0)
ElseIf (mode = 2) Then
GraphicsWindow.BrushColor = "Red"
rad = 20+Math.GetRandomNumber(20)
temp = Shapes.AddEllipse(rad,rad)
LDPhysics.AddMovingShape(temp,0.5,0.8,1)
LDPhysics.SetPosition(temp,Math.GetRandomNumber(600),50,0)
Else
GraphicsWindow.BrushColor = "Green"
temp = Shapes.AddTriangle(0,0,20+Math.GetRandomNumber(20),0,0,2+Math.GetRandomNumber(20))
LDPhysics.AddMovingShape(temp,0.5,0.8,1)
LDPhysics.SetPosition(temp,Math.GetRandomNumber(600),50,0)
EndIf
EndFor
panLeft = 0
panRight = 0
GraphicsWindow.keyDown = OnkeyDown
GraphicsWindow.keyUp = OnkeyUp
Sub OnkeyDown
k = GraphicsWindow.LastKey
If (k = "Left") Then
panLeft = 1
ElseIf (k = "Right") Then
panRight = 1
EndIf
EndSub
Sub OnkeyUp
k = GraphicsWindow.LastKey
If (k = "Left") Then
panLeft = 0
ElseIf (k = "Right") Then
panRight = 0
EndIf
EndSub
LDPhysics.SetBoundaries(-1,1+GraphicsWindow.Width,0,GraphicsWindow.Height)
While ("True")
handleEvents()
LDPhysics.DoTimestep()
Program.Delay(20)
EndWhile
Sub handleEvents
speed = 10
If (panLeft = 1) Then
LDPhysics.PanView(-speed,0)
EndIf
If (panRight = 1) Then
LDPhysics.PanView(speed,0)
EndIf
EndSub
Page 37
Other Samples
Here are some screenshots of other samples included.
Cogs.sb
Intermeshing cogs that turn.
Page 38
Joints.sb
Some advanced joints, including motors, pulleys and gears.
Page 39
physics-sample.sb
Bouncing balls with ropes and chains.
Page 40
physics-sample-car.sb
A moving car.
physics-sample-pencil.sb
Attached and grouped shapes.
Page 41
physics-sample-rope-bridge.sb
Many interacting shapes.
Page 42
physics-sample-water.sb
Moving water molecules.
Page 43
pool.sb
A full pool game.
TopDownCar.sb
A car with skid and crash detection in zero gravity, top-down.
Page 44
ChainColour
PARAMETER
LoadImagesAsCircles
PARAMETER
Toggle whether image shapes will be loaded as circles - "True" or "False" (default is "False").
MaxPolygonVertices
PARAMETER
The physics engine maximum number of vertices on convex polygons (default 8).
MaxProxies
PARAMETER
PositionIterations
PARAMETER
RopeColour
PARAMETER
Scaling
PARAMETER
The physics engine scaling (pixel/m, default 10). It is not recommended to change this.
TimeStep
PARAMETER
VelocityIterations
PARAMETER
VelocityThreshold
PARAMETER
The physics engine velocity threshold for inelastic collisions 'sticky walls' (default 1).
AddChain(shape1,shape2)
OPERATION
Page 45
AddExplosion(posX,posY,power,damping,colour)
OPERATION
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).
Returns
None.
AddFixedAnchor(posX,posY)
OPERATION
AddFixedShape(shapeName,friction,restitution)
OPERATION
Add an existing Small Basic 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.
Page 46
AddInactiveShape(shapeName)
OPERATION
Add an existing Small Basic shape to the physics engine as an inactive (non-dynamic and noninteracting) shape which only moves with the PanView method.
shapeName
The name of the shape.
Returns
None.
AddMovingAnchor(posX,posY)
OPERATION
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)
OPERATION
Add an existing Small Basic 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.
Page 47
AddRope(shape1,shape2)
OPERATION
AttachShapes(shape1,shape2)
OPERATION
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)
OPERATION
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.
Page 48
"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.
Returns
The joint name.
AttachShapesWithRotation(shape1,shape2)
OPERATION
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)
OPERATION
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 "".
Page 49
BrakeTire(shapeName)
OPERATION
DetachJoint(jointName)
OPERATION
DetachShapes(shape1,shape2)
OPERATION
Page 50
DisconnectShape(shapeName)
OPERATION
Disconnect shape from the physics engine without deleting the shape.
shapeName
The shape name.
Returns
None.
DoTimestep()
OPERATION
FollowShapeX(shapeName)
OPERATION
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)
OPERATION
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.
GetAllShapesAt(posX,posY)
OPERATION
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 X coordinate.
Page 51
GetAngle(shapeName)
OPERATION
GetCollisions(shapeName)
OPERATION
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 "").
GetContacts(posX,posY,distance)
OPERATION
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)
OPERATION
GetMass(shapeName)
OPERATION
Page 52
GetPan()
OPERATION
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)
OPERATION
GetRotation(shapeName)
OPERATION
GetShapeAt(posX,posY)
OPERATION
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 X coordinate.
Returns
The shape name at the input position or "".
GetTireInformation(shapeName)
OPERATION
Skid (if this value exceeds the property AntiSkid, then the tire is skidding)
Page 53
shapeName
The tire shape.
Returns
An array of information, indexed by the information name, e.g. "Skid".
GetTireProperties(shapeName)
OPERATION
shapeName
The tire shape.
Returns
An array of properties, indexed by the property name, e.g. "AntiSkid".
GetVelocity(shapeName)
OPERATION
GroupShapes(shape1,shape2)
OPERATION
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()
OPERATION
Page 54
MoveTire(shapeName,force)
OPERATION
Page 55
PanView(panHorizontal,panVertical)
OPERATION
RayCast(shapeName,angle,distance)
OPERATION
ReadJson(filename,scale,reverseY)
OPERATION
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").
Returns
A text array containing the LDPhysics commands used to create the model.
RemoveChain(shapeName)
OPERATION
Remove a chain.
Page 56
RemoveFrozen()
OPERATION
Removes all frozen shapes - outside the AABB for the engine.
Returns
None.
RemoveRope(shapeName)
OPERATION
Remove a rope.
shapeName
The rope name.
Returns
None.
RemoveShape(shapeName)
OPERATION
Remove a shape.
shapeName
The name of the shape.
Returns
None.
Reset()
OPERATION
SetAABB(minX,maxX,minY,maxY)
OPERATION
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 200).
minY
The top coordinate of the universe (default -100).
Page 57
SetAngle(shapeName, angle)
OPERATION
SetBoundaries(left,right,top,bottom)
OPERATION
Set solid boundaries (positioning a boundary outside the GraphicsWindow removes it).
left
The left bounday X value.
right
The right bounday X value.
top
The top bounday Y value.
bottom
The bottom (ground) boundary Y value.
Returns
None.
SetBullet(shapeName)
OPERATION
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)
OPERATION
Page 58
SetForce(shapeName,forceX,forceY)
OPERATION
SetGravity(gravX,gravY)
OPERATION
SetGroup(shapeName,group,mask)
OPERATION
Page 59
SetImpulse(shapeName,impulseX,impulseY)
OPERATION
SetJointMotor(jointName,speed,maxForce)
OPERATION
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.
Returns
None.
SetPosition(shapeName,posX,posY,angle)
OPERATION
Page 60
SetRotation(shapeName,rotation)
OPERATION
SetShapeGravity(shapeName,gravX,gravY)
OPERATION
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)
OPERATION
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.
Returns
None.
SetTireProperties(shapeName,properties)
OPERATION
Page 61
shapeName
The tire shape.
Returns
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)
OPERATION
SetVelocity(shapeName,velX,velY)
OPERATION
TimestepControl(timestep,velocityIterations,positionIterations)
OPERATION
Modify default time-step 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.
Page 62
TurnTire(shapeName,torque)
OPERATION
ToggleMoving(shapeName)
OPERATION
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.
Returns
None.
ToggleRotation(shapeName)
OPERATION
Toggle a shape to not rotate and vice-versa. This method toggles the rotation property for fixed
and moving shapes.
shapeName
The shape name.
Returns
None.
ToggleSensor(shapeName)
OPERATION
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.
Returns
None.
UngroupShapes(shape1,shape2)
OPERATION
Page 63
UnsetBullet(shapeName)
OPERATION
Unset a shape as a bullet. This reverts the shape to normal collision detection.
shapeName
The shape name.
Returns
None.
WakeAll()
OPERATION
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)
OPERATION
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.
Returns
None.
Page 64