Class PhysicsWorld
A 2D rigid body physics world, wrapping a shaded Box2D (JBox2D) simulation in an idiomatic Codename One API.
The world works in pixels on the outside and meters internally (Box2D is
tuned for objects a few meters in size, so feeding it pixels directly produces a
sluggish, unstable simulation). The conversion is governed by
#setPixelsPerMeter(float) (default 30). The screen y axis points down while
Box2D's points up; the wrapper flips y so application code stays in screen
coordinates -- so a positive gravity y value pulls bodies down the screen.
Drive the simulation from a com.codename1.gaming.GameView update loop:
PhysicsWorld world = new PhysicsWorld(0, 600); // gravity 600 px/s^2 downward
PhysicsBody ground = world.createBox(0, 460, 320, 40, BodyType.STATIC);
PhysicsBody crate = world.createBox(160, 0, 32, 32, BodyType.DYNAMIC);
crate.setLinkedSprite(crateSprite);
// in update(dt):
world.step((float) dt); // integrates and syncs linked sprites
-
Constructor Summary
ConstructorsConstructorDescriptionPhysicsWorld(float gravityXPx, float gravityYPx) Creates a world with the given gravity in pixels per second squared. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddContactListener(ContactListener listener) Registers a contact listener notified when bodies start and stop touching.Creates a rectangular body centered at the given pixel position.createCircle(float xPx, float yPx, float radiusPx, BodyType type) Creates a circular body centered at the given pixel position.createDistanceJoint(PhysicsBody a, PhysicsBody b, float anchorAXPx, float anchorAYPx, float anchorBXPx, float anchorBYPx, float frequencyHz, float dampingRatio) A spring/rod joint that keeps the two pixel anchor points a fixed distance apart.createMouseJoint(PhysicsBody ground, PhysicsBody target, float targetXPx, float targetYPx, float maxForce) A mouse joint that pullstargettoward a moving pixel point with a capped force -- the basis for dragging a body with a finger.createPolygon(float xPx, float yPx, float[] verticesPx, BodyType type) Creates a convex polygon body.createPrismaticJoint(PhysicsBody a, PhysicsBody b, float anchorXPx, float anchorYPx, float axisX, float axisY) A prismatic (slider) joint: bodybmay only translate along the given pixel axis relative to bodya(e.g. a piston or an elevator).createRevoluteJoint(PhysicsBody a, PhysicsBody b, float anchorXPx, float anchorYPx) A pin/hinge joint: the two bodies rotate freely around the shared pixel anchor (e.g. a wheel on an axle, a ragdoll elbow).createShape(float xPx, float yPx, Shape shape, BodyType type) Creates a body whose collision outline is a Codename Onecom.codename1.ui.geom.Shape-- typically acom.codename1.ui.geom.GeneralPath-- so you can describe a hit-shape with the same geometry API you draw with.createWeldJoint(PhysicsBody a, PhysicsBody b, float anchorXPx, float anchorYPx) A weld joint: the two bodies are locked rigidly together at the pixel anchor (as if glued).voidRenders the world's collision shapes, joints and (optionally) bounding boxes onto the givencom.codename1.ui.Graphics, for debugging.voiddestroyJoint(PhysicsJoint joint) Removes a joint from the world.Returns the underlying shaded Box2D world for advanced use.floatvoidremoveBody(PhysicsBody body) Removes a body from the world.voidremoveContactListener(ContactListener listener) voidsetDebugDrawFlags(boolean shapes, boolean joints, boolean boundingBoxes) Selects what#debugDraw(com.codename1.ui.Graphics)renders.voidsetDebugFillAlpha(int alpha) Sets the alpha (0..255) used to fill solid shapes in#debugDraw(com.codename1.ui.Graphics); shape outlines stay opaque.voidsetGravity(float gxPx, float gyPx) Sets gravity in pixels per second squared (positive y is downward).voidsetPixelsPerMeter(float ppm) The pixels-per-meter scale used to convert between screen and simulation units.voidsetPositionIterations(int positionIterations) voidsetVelocityIterations(int velocityIterations) voidstep(float deltaSeconds) Advances the simulation by the given time step (seconds) and then syncs every body's transform into its linkedPhysicsLinkable(typically acom.codename1.gaming.Sprite).voidPushes each body's current transform into its linked object, converting meters to pixels and flipping the y axis.
-
Constructor Details
-
PhysicsWorld
public PhysicsWorld(float gravityXPx, float gravityYPx) Creates a world with the given gravity in pixels per second squared. A positive y pulls bodies down the screen.
-
-
Method Details
-
setPixelsPerMeter
public void setPixelsPerMeter(float ppm) The pixels-per-meter scale used to convert between screen and simulation units. Set this once before creating bodies. -
getPixelsPerMeter
public float getPixelsPerMeter() -
setVelocityIterations
public void setVelocityIterations(int velocityIterations) -
setPositionIterations
public void setPositionIterations(int positionIterations) -
setGravity
public void setGravity(float gxPx, float gyPx) Sets gravity in pixels per second squared (positive y is downward). -
step
public void step(float deltaSeconds) Advances the simulation by the given time step (seconds) and then syncs every body's transform into its linkedPhysicsLinkable(typically acom.codename1.gaming.Sprite). Call once per frame from the game loop. -
syncSprites
public void syncSprites()Pushes each body's current transform into its linked object, converting meters to pixels and flipping the y axis. Called automatically by#step(float). -
createBox
Creates a rectangular body centered at the given pixel position. -
createCircle
Creates a circular body centered at the given pixel position. -
createPolygon
Creates a convex polygon body. The vertices are pixel offsets relative to the body center, as alternating x,y pairs (soverticesPx.lengthmust be even). -
createShape
Creates a body whose collision outline is a Codename One
com.codename1.ui.geom.Shape-- typically acom.codename1.ui.geom.GeneralPath-- so you can describe a hit-shape with the same geometry API you draw with. The shape's coordinates are pixel offsets relative to the body center(xPx, yPx); Bezier curves are flattened to line segments.Each subpath becomes one fixture on the body (so a figure with several disconnected outlines yields a compound body). A subpath is converted as follows:
-
A closed, convex subpath of at most
Settings.maxPolygonVertices(8) points becomes a solidPolygonShape-- usable by bodies of anyBodyType. -
Any other subpath (concave, more than 8 points, or left open) becomes a
ChainShape-- an exact but one-sided edge outline. Chains are ideal forBodyType#STATICterrain; a dynamic body needs convex pieces to behave as a solid, so split a concave dynamic shape into convex subpaths.
For a single, simple convex hull
#createPolygon(float, float, float[], BodyType)is a lighter-weight alternative. -
-
removeBody
Removes a body from the world. -
addContactListener
Registers a contact listener notified when bodies start and stop touching. -
removeContactListener
-
getNativeWorld
Returns the underlying shaded Box2D world for advanced use. Coordinates on the native world are in meters with y pointing up. -
createRevoluteJoint
public PhysicsJoint createRevoluteJoint(PhysicsBody a, PhysicsBody b, float anchorXPx, float anchorYPx) A pin/hinge joint: the two bodies rotate freely around the shared pixel anchor (e.g. a wheel on an axle, a ragdoll elbow). -
createDistanceJoint
public PhysicsJoint createDistanceJoint(PhysicsBody a, PhysicsBody b, float anchorAXPx, float anchorAYPx, float anchorBXPx, float anchorBYPx, float frequencyHz, float dampingRatio) A spring/rod joint that keeps the two pixel anchor points a fixed distance apart.frequencyHz0 makes it a rigid rod; a positive value makes it a softer spring (withdampingRatio0..1). -
createWeldJoint
A weld joint: the two bodies are locked rigidly together at the pixel anchor (as if glued). -
createPrismaticJoint
public PhysicsJoint createPrismaticJoint(PhysicsBody a, PhysicsBody b, float anchorXPx, float anchorYPx, float axisX, float axisY) A prismatic (slider) joint: bodybmay only translate along the given pixel axis relative to bodya(e.g. a piston or an elevator). -
createMouseJoint
public PhysicsJoint createMouseJoint(PhysicsBody ground, PhysicsBody target, float targetXPx, float targetYPx, float maxForce) A mouse joint that pullstargettoward a moving pixel point with a capped force -- the basis for dragging a body with a finger.groundis any body (typically a static one); update the point each frame withPhysicsJoint#setTarget(float, float). -
destroyJoint
Removes a joint from the world. -
setDebugDrawFlags
public void setDebugDrawFlags(boolean shapes, boolean joints, boolean boundingBoxes) Selects what#debugDraw(com.codename1.ui.Graphics)renders. By default it draws collision shapes and joints; bounding boxes are off. -
debugDraw
Renders the world's collision shapes, joints and (optionally) bounding boxes onto the givencom.codename1.ui.Graphics, for debugging. Coordinates use the same pixel scale and y-flip as the bodies, so the overlay lines up with the sprites they drive. Call it from a component'spaint, onto an off-screencom.codename1.ui.Image, or any other 2D drawing surface. See#setDebugDrawFlags(boolean, boolean, boolean)to choose what is drawn. -
setDebugFillAlpha
public void setDebugFillAlpha(int alpha) Sets the alpha (0..255) used to fill solid shapes in#debugDraw(com.codename1.ui.Graphics); shape outlines stay opaque. The default (90) is a light translucent fill.
-