SlideShare una empresa de Scribd logo
1 de 28
Descargar para leer sin conexión
Box2D	
  and	
  libGDX	
  
Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
Box2D	
  
•  Free	
  open	
  source	
  2D	
  physics	
  simulator	
  engine	
  
wriEen	
  in	
  C++	
  
•  Has	
  been	
  used	
  for	
  example	
  in	
  Angry	
  Birds,	
  
Tiny	
  Wings	
  
•  Has	
  been	
  ported	
  to	
  Java,	
  Flash,	
  C#,	
  JavaScript	
  
•  Programs	
  that	
  use	
  Box2D	
  
– libGDX,	
  Unity,	
  iOS	
  SpriteKit,	
  GameMaker	
  
Studio	
  ...	
  
Concepts	
  
•  World	
  
–  CollecNon	
  of	
  bodies,	
  fixtures,	
  joints	
  that	
  interact	
  
•  Body	
  
–  Game	
  Objects	
  that	
  contains	
  fixtures	
  
–  Dynamic	
  (spaceship),	
  StaAc	
  (ground)	
  and	
  KinemaAc	
  
–  Fixture	
  
•  Body	
  has	
  Fixture!	
  
•  Density:	
  Mass	
  per	
  square	
  meter:	
  bowling	
  ball	
  dense,	
  balloon	
  not	
  
•  FricAon:	
  When	
  sliding	
  along	
  something,	
  amount	
  of	
  opposite	
  force	
  
•  ResAtuAon:	
  How	
  bouncy	
  object	
  is	
  (0	
  =	
  does	
  not	
  bounce,	
  1	
  =	
  very	
  bouncy)	
  	
  
•  Shape	
  
–  Fixture	
  has	
  Shape	
  
–  Polygon	
  or	
  Circle,	
  can	
  be	
  mixed	
  
•  Joint	
  
–  Holds	
  bodies	
  together.	
  Several	
  joints	
  available.	
  
World	
   Body	
   Fixture	
   Shape	
  
// Create array full of bodies
Array<Body> bodies = new Array<Body>();
// Take all bodies from world and put them into array
world.getBodies(bodies);
// Get shape of first body, it's first fixture and it's shape
Shape s = bodies.get(0).getFixtureList().get(0).getShape();
Units	
  
•  Box2D	
  uses	
  floaAng	
  points	
  
•  Tuned	
  for	
  meter	
  –	
  kilogram	
  –	
  second	
  (KMS)	
  
•  OpNmized	
  so	
  that	
  shapes	
  can	
  move	
  between	
  
0.1	
  –	
  10	
  meters	
  
•  It's	
  tempNng	
  to	
  use	
  pixel	
  as	
  units	
  -­‐>	
  leads	
  to	
  
poor	
  simulaNon	
  and	
  weird	
  behavior	
  
– Keep	
  moving	
  objects	
  between	
  0.1	
  –	
  10	
  meters!	
  
•  DO	
  NOT	
  USE	
  PIXELS!	
  DO	
  NOT!	
  
Units	
  in	
  libGDX	
  
•  Window/real	
  resoluNon	
  <-­‐>	
  World	
  Units	
  <-­‐>	
  
Box2D	
  units	
  (meters)	
  
•  How	
  to	
  handle	
  this?	
  Just	
  use	
  meters	
  in	
  World	
  
Units,	
  so	
  you	
  don't	
  have	
  to	
  make	
  any	
  
conversions	
  
– float width = 640.0f / 100.0f
– float height = 400.0f / 100.0f
– camera = new OrthographicCamera();
– camera.setToOrtho(false, width, height);
CreaNng	
  a	
  World	
  
// Create world and set it's gravity!
// true => allow body sleeping
World world = new World(new Vector2(0,
-9.8f), true);
// Next steps: create a body to the world
	
  
Body	
  Types	
  
•  Dynamic	
  Body	
  
– Player	
  and	
  other	
  actors	
  on	
  screen	
  
•  StaAc	
  Body	
  
– Walls,	
  floors	
  and	
  so	
  on	
  
•  KinemaAc	
  Body	
  
– Moving	
  pladorm	
  in	
  pladorm	
  game	
  
– It's	
  a	
  staNc	
  body	
  that	
  can	
  also	
  move	
  and	
  rotate.	
  
When	
  dynamic	
  body	
  collides,	
  kinemaNc	
  body	
  
"wins"	
  	
  
Bodies	
  
•  Bodies	
  are	
  objects	
  in	
  physics	
  space	
  
– Does	
  not	
  hold	
  texture!	
  So	
  it's	
  not	
  visible!	
  
•  Hold	
  properNes	
  like	
  
– mass,	
  velocity,	
  locaNon,	
  angle	
  
•  Define	
  size	
  and	
  shape	
  of	
  the	
  body	
  using	
  a	
  
fixture	
  
•  Shape	
  can	
  be	
  circle	
  or	
  polygon	
  or	
  a	
  mixture	
  of	
  
these!	
  
CreaNng	
  a	
  Body	
  
•  To	
  create	
  body,	
  use	
  
–  // Create BodyDef..
–  Body playerBody = world.createBody(BodyDef);
•  BodyDef?	
  
–  Type	
  of	
  body?	
  StaNc,	
  kinemaNc,	
  dynamic	
  
–  PosiNon	
  
•  Ager	
  creaNon,	
  add	
  a	
  Fixture	
  to	
  the	
  body	
  
–  Density,	
  ResNtuNon	
  (bouncy?),	
  fricNon	
  (slippery?),	
  
shape	
  (circle	
  or	
  polygon)	
  
–  playerBody.createFixture(playerFixtureDef);
	
  
CreaNng	
  a	
  Body	
  
public void createPlayerBody() {
// *** 1) DEFINITION OF A BODY *** /
// Body Definition
BodyDef myBodyDef = new BodyDef();
// It's a body that moves
myBodyDef.type = BodyDef.BodyType.DynamicBody;
// Initial position is centered up (width = 12.8, height = 7.2)
// This position is the CENTER of the shape!
myBodyDef.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2);
// *** 2) CREATE THE BODY *** /
Body playerBody = world.createBody(myBodyDef);
// *** 3) FIXTURE FOR THE BODY *** /
// Create fixture and add the shape to it
FixtureDef playerFixtureDef = new FixtureDef();
// Mass per square meter (kg^m2)
playerFixtureDef.density = 1;
// How bouncy object? Very bouncy [0,1]
playerFixtureDef.restitution = 1.0f;
// How slipper object? [0,1]
playerFixtureDef.friction = 0.5f;
// Create circle shape.
CircleShape circleshape = new CircleShape();
circleshape.setRadius(0.1f);
// Add the shape to the fixture
playerFixtureDef.shape = circleshape;
// Add fixture to the body
playerBody.createFixture(playerFixtureDef);
}
About	
  Rendering	
  
•  Box2D	
  holds	
  the	
  physics,	
  it's	
  not	
  about	
  
rendering	
  
– For	
  every	
  render	
  call,	
  update	
  (step)	
  the	
  world	
  
•  To	
  render,	
  map	
  some	
  texture	
  to	
  the	
  posiNon	
  
of	
  the	
  playerBody!	
  
•  For	
  debugging,	
  use	
  debugRenderer	
  
Example	
  About	
  Rendering	
  
public class Box2DExample extends ApplicationAdapter {
private SpriteBatch batch;
public static final boolean DEBUG_PHYSICS = true;
public static final float WORLD_WIDTH = 6.4f;
public static final float WORLD_HEIGHT = 4.0f;
private OrthographicCamera camera;
private World world;
private Box2DDebugRenderer debugRenderer;
@Override
public void create () {
camera = new OrthographicCamera();
camera.setToOrtho(false, WORLD_WIDTH, WORLD_HEIGHT);
batch = new SpriteBatch();
world = new World(new Vector2(0f, -9.81f), true);
debugRenderer = new Box2DDebugRenderer();
createPlayerBody();
}
public void createPlayerBody() { ... }
@Override
public void render () {
batch.setProjectionMatrix(camera.combined);
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if(DEBUG_PHYSICS) {
debugRenderer.render(world, camera.combined);
}
batch.begin();
// Do some drawing
batch.end();
world.step(1/60f, 6, 2);
}
}
Rendering	
  (Debug)	
  
// Create the renderer (in create...)
Box2DDebugRenderer debugRenderer =
new Box2DDebugRenderer(true, // draw bodies
false, // joints
false, // drawAABBs
false, // drawInactiveBodies
false, // drawVelocities
false); // drawContacts
public void render() {
...
debugRenderer.render(world, camera.combined);
world.step(1 / 60f, 6, 2);
...
}
Update	
  World:	
  Stepping	
  
•  To	
  update	
  world,	
  we	
  need	
  to	
  tell	
  the	
  world	
  to	
  step	
  
// Advance simulation 1/60 of a sec. This should
// correspond to framerate in your game
float timeStep = 1/60.0f;
// How strongly to correct velocity when colliding
// More higher, more correct simulation but cost of performance
int velocityIterations = 6;
// How strongly to correct position when colliding
// More higher, more correct simulation but cost of performance
int positionIterations = 2;
world.step(timeStep, velocityIterations, positionIterations);
•  Do	
  this	
  at	
  the	
  end	
  of	
  the	
  render()	
  call	
  
Variable	
  Nmestep	
  
•  If	
  you	
  have	
  following	
  
– world.step(1/60f, 6, 2);
•  SimulaNon	
  can	
  be	
  ruined	
  if	
  machine	
  is	
  not	
  
able	
  to	
  run	
  at	
  60fps	
  
•  You	
  could	
  calculate	
  the	
  game	
  speed	
  and	
  add	
  it	
  
to	
  stepping	
  
– world.step(framerate, 6, 2);
•  Problem	
  now	
  is	
  that	
  your	
  game	
  can	
  run	
  very	
  
very	
  fast	
  or	
  very	
  very	
  slow	
  
	
  
public void render() {
...
doPhysicsStep();
}
private double accumulator = 0;
private double currentTime = TimeUtils.millis() / 1000.0;
private void doPhysicsStep() {
// We are not using Gdx.graphics.getDeltaTime(), it may not
// be accurate enough.
// Current time
double newTime = TimeUtils.millis() / 1000.0;
// How much time since last call?
double deltaTime = newTime - currentTime;
currentTime = newTime;
float TIME_STEP = 1/60f;
// If it took ages (> 0.25 => 4 fps)
// FIXED Upper limit to prevent going really slow
if(deltaTime > 0.25) {
deltaTime = 0.25;
}
accumulator += deltaTime;
while (accumulator >= TIME_STEP) {
world.step(TIME_STEP, 6, 2);
accumulator -= TIME_STEP;
}
}
"Ground"	
  
public void createGround() {
// *** 1) DEFINITION OF A BODY *** /
// Body Definition
BodyDef myBodyDef = new BodyDef();
// This body won't move
myBodyDef.type = BodyDef.BodyType.StaticBody;
// Initial position is centered up
// This position is the CENTER of the shape!
myBodyDef.position.set(WORLD_WIDTH / 2, 0.25f);
// *** 2) CREATE THE BODY *** /
Body groundBody = world.createBody(myBodyDef);
// *** 3) FIXTURE FOR THE BODY *** /
// Create shape
PolygonShape groundBox = new PolygonShape();
// Real width and height is 2 X this!
groundBox.setAsBox( WORLD_WIDTH/2 , 0.25f);
// Add shape to fixture, 0.0f is density.
// Using method createFixture(Shape, density) no need
// to create FixtureDef object as on createPlayer!
groundBody.createFixture(groundBox, 0.0f);
}
Draw	
  texture	
  to	
  body	
  pos!	
  
public void render() {
...
batch.draw(texture,
playerBody.getPosition().x,
playerBody.getPosition.y);
}
Draw	
  texture	
  to	
  body	
  pos!	
  
batch.draw(playerTexture,
playerBody.getPosition().x - playerRadius,
playerBody.getPosition().y - playerRadius,
playerRadius, // originX
playerRadius, // originY
playerRadius * 2, // width
playerRadius * 2, // height
1.0f, // scaleX
1.0f, // scaleY
playerBody.getTransform().getRotation() * MathUtils.radiansToDegrees,
0, // Start drawing from x = 0
0, // Start drawing from y = 0
playerTexture.getWidth(), // End drawing x
playerTexture.getHeight(), // End drawing y
false, // flipX
false); // flipY
Create	
  Body	
  and	
  Add	
  User	
  Data	
  
public void createJussi(float x, float y) {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(x,y);
Body body = world.createBody(bodyDef);
PolygonShape dynamicCircle = new PolygonShape();
dynamicCircle.setAsBox(0.5f, 0.5f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = dynamicCircle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.8f;
body.createFixture(fixtureDef);
// user data can be anything! any object!
body.setUserData(jussiTexture);
}
Create	
  Body	
  and	
  Add	
  User	
  Data	
  
public void render() {
...
debugRenderer.render(world, camera.combined);
// populate the array with bodies
world.getBodies(bodies);
// iterate the bodies
for (Body body : bodies) {
if(body.getUserData() != null && body.getUserData() == jussiTexture) {
batch.draw((Texture) body.getUserData(),
body.getPosition().x - 0.5f,
body.getPosition().y - 0.5f,
...
body.getTransform().getRotation() * MathUtils.radiansToDegrees,
...
false
);
}
}
doPhysicsStep();
}
FORCES	
  AND	
  IMPULSES	
  
Forces	
  and	
  Impulses	
  
•  To	
  move	
  things	
  around,	
  you'll	
  need	
  to	
  apply	
  
forces	
  or	
  impulses	
  to	
  a	
  body	
  
•  Force	
  
–  Gradually	
  over	
  Nme	
  change	
  velocity	
  of	
  a	
  body	
  
–  Also	
  angular	
  force	
  available,	
  torque	
  (twisNng	
  strength)	
  
•  Impulse	
  
–  Change	
  velocity	
  immediately	
  
•  Of	
  course	
  you	
  can	
  just	
  change	
  the	
  posiNon	
  of	
  a	
  
body	
  
Examples	
  
// gradually accelerate right
body.applyForceToCenter(50f, 0, true);
// Jump up
body.applyLinearImpulse(new Vector2(0f, 20f),
body.getWorldCenter(),
true);
COLLISIONS	
  
Collision	
  
world.setContactListener(new ContactListener() {
@Override
public void beginContact(Contact contact) {
Body bodyA = contact.getFixtureA().getBody();
Body bodyB = contact.getFixtureB().getBody();
}
@Override
public void endContact(Contact contact) { }
@Override
public void preSolve(Contact contact, Manifold oldManifold) { }
@Override
public void postSolve(Contact contact, ContactImpulse impulse) { }
});

Más contenido relacionado

La actualidad más candente

HoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingHoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingTakashi Yoshinaga
 
Converting Scene Data to DOTS – Unite Copenhagen 2019
Converting Scene Data to DOTS – Unite Copenhagen 2019Converting Scene Data to DOTS – Unite Copenhagen 2019
Converting Scene Data to DOTS – Unite Copenhagen 2019Unity Technologies
 
Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲吳錫修 (ShyiShiou Wu)
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Unity Technologies
 
Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019Unity Technologies
 
Test Driven Cocos2d
Test Driven Cocos2dTest Driven Cocos2d
Test Driven Cocos2dEric Smith
 
Introduction to Game Programming Tutorial
Introduction to Game Programming TutorialIntroduction to Game Programming Tutorial
Introduction to Game Programming TutorialRichard Jones
 
Intro to Game Programming
Intro to Game ProgrammingIntro to Game Programming
Intro to Game ProgrammingRichard Jones
 
Unity遊戲程式設計(15) 實作Space shooter遊戲
Unity遊戲程式設計(15) 實作Space shooter遊戲Unity遊戲程式設計(15) 實作Space shooter遊戲
Unity遊戲程式設計(15) 實作Space shooter遊戲吳錫修 (ShyiShiou Wu)
 
Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019
Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019
Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019Unity Technologies
 
Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.UA Mobile
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simplerAlexander Mostovenko
 
Ujug07presentation
Ujug07presentationUjug07presentation
Ujug07presentationBill Adams
 
Tools for developing Android Games
 Tools for developing Android Games Tools for developing Android Games
Tools for developing Android GamesPlatty Soft
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 

La actualidad más candente (20)

HoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingHoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial Mapping
 
Converting Scene Data to DOTS – Unite Copenhagen 2019
Converting Scene Data to DOTS – Unite Copenhagen 2019Converting Scene Data to DOTS – Unite Copenhagen 2019
Converting Scene Data to DOTS – Unite Copenhagen 2019
 
Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
 
Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019
 
Games 3 dl4-example
Games 3 dl4-exampleGames 3 dl4-example
Games 3 dl4-example
 
Test Driven Cocos2d
Test Driven Cocos2dTest Driven Cocos2d
Test Driven Cocos2d
 
Introduction to Game Programming Tutorial
Introduction to Game Programming TutorialIntroduction to Game Programming Tutorial
Introduction to Game Programming Tutorial
 
Sequence diagrams
Sequence diagramsSequence diagrams
Sequence diagrams
 
Intro to Game Programming
Intro to Game ProgrammingIntro to Game Programming
Intro to Game Programming
 
Unity遊戲程式設計(15) 實作Space shooter遊戲
Unity遊戲程式設計(15) 實作Space shooter遊戲Unity遊戲程式設計(15) 實作Space shooter遊戲
Unity遊戲程式設計(15) 實作Space shooter遊戲
 
Unity3 d devfest-2014
Unity3 d devfest-2014Unity3 d devfest-2014
Unity3 d devfest-2014
 
Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019
Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019
Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019
 
Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
Ujug07presentation
Ujug07presentationUjug07presentation
Ujug07presentation
 
Tools for developing Android Games
 Tools for developing Android Games Tools for developing Android Games
Tools for developing Android Games
 
Unity 13 space shooter game
Unity 13 space shooter gameUnity 13 space shooter game
Unity 13 space shooter game
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 

Destacado

Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
Building games-with-libgdx
Building games-with-libgdxBuilding games-with-libgdx
Building games-with-libgdxJumping Bean
 
LibGDX: Cross Platform Game Development
LibGDX: Cross Platform Game DevelopmentLibGDX: Cross Platform Game Development
LibGDX: Cross Platform Game DevelopmentIntel® Software
 

Destacado (6)

Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Building games-with-libgdx
Building games-with-libgdxBuilding games-with-libgdx
Building games-with-libgdx
 
LibGDX: Cross Platform Game Development
LibGDX: Cross Platform Game DevelopmentLibGDX: Cross Platform Game Development
LibGDX: Cross Platform Game Development
 

Similar a Box2D and libGDX

Box2D with SIMD in JavaScript
Box2D with SIMD in JavaScriptBox2D with SIMD in JavaScript
Box2D with SIMD in JavaScriptIntel® Software
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Gdc09 Minigames
Gdc09 MinigamesGdc09 Minigames
Gdc09 MinigamesSusan Gold
 
Game development with Cocos2d
Game development with Cocos2dGame development with Cocos2d
Game development with Cocos2dVinsol
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsNick Pruehs
 
Chipmunk physics presentation
Chipmunk physics presentationChipmunk physics presentation
Chipmunk physics presentationCarl Brown
 
Creating physics game in 1 hour
Creating physics game in 1 hourCreating physics game in 1 hour
Creating physics game in 1 hourLinkou Bian
 
Testing a 2D Platformer with Spock
Testing a 2D Platformer with SpockTesting a 2D Platformer with Spock
Testing a 2D Platformer with SpockAlexander Tarlinder
 
Get Into Sprite Kit
Get Into Sprite KitGet Into Sprite Kit
Get Into Sprite Kitwaynehartman
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
Useful Tools for Making Video Games - Newton (2008)
Useful Tools for Making Video Games - Newton (2008)Useful Tools for Making Video Games - Newton (2008)
Useful Tools for Making Video Games - Newton (2008)Korhan Bircan
 
public void turnRight(double degrees) {rotationInDegrees + - = deg.pdf
public void turnRight(double degrees) {rotationInDegrees + - = deg.pdfpublic void turnRight(double degrees) {rotationInDegrees + - = deg.pdf
public void turnRight(double degrees) {rotationInDegrees + - = deg.pdfisenbergwarne4100
 
Demo creating-physics-game.
Demo creating-physics-game.Demo creating-physics-game.
Demo creating-physics-game.sagaroceanic11
 
Academy PRO: Unity 3D. Environment
Academy PRO: Unity 3D. EnvironmentAcademy PRO: Unity 3D. Environment
Academy PRO: Unity 3D. EnvironmentBinary Studio
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreRemy Sharp
 
Sceneform SDK на практиці - UA Mobile 2019
Sceneform SDK на практиці - UA Mobile 2019Sceneform SDK на практиці - UA Mobile 2019
Sceneform SDK на практиці - UA Mobile 2019UA Mobile
 
Sceneform SDK на практиці - UA Mobile 2019
Sceneform SDK на практиці - UA Mobile 2019Sceneform SDK на практиці - UA Mobile 2019
Sceneform SDK на практиці - UA Mobile 2019Eugene Kurko
 

Similar a Box2D and libGDX (20)

Box2D with SIMD in JavaScript
Box2D with SIMD in JavaScriptBox2D with SIMD in JavaScript
Box2D with SIMD in JavaScript
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Basics cocos2d
Basics cocos2dBasics cocos2d
Basics cocos2d
 
Gdc09 Minigames
Gdc09 MinigamesGdc09 Minigames
Gdc09 Minigames
 
Game development with Cocos2d
Game development with Cocos2dGame development with Cocos2d
Game development with Cocos2d
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine Basics
 
Chipmunk physics presentation
Chipmunk physics presentationChipmunk physics presentation
Chipmunk physics presentation
 
Creating physics game in 1 hour
Creating physics game in 1 hourCreating physics game in 1 hour
Creating physics game in 1 hour
 
Testing a 2D Platformer with Spock
Testing a 2D Platformer with SpockTesting a 2D Platformer with Spock
Testing a 2D Platformer with Spock
 
Get Into Sprite Kit
Get Into Sprite KitGet Into Sprite Kit
Get Into Sprite Kit
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
Useful Tools for Making Video Games - Newton (2008)
Useful Tools for Making Video Games - Newton (2008)Useful Tools for Making Video Games - Newton (2008)
Useful Tools for Making Video Games - Newton (2008)
 
public void turnRight(double degrees) {rotationInDegrees + - = deg.pdf
public void turnRight(double degrees) {rotationInDegrees + - = deg.pdfpublic void turnRight(double degrees) {rotationInDegrees + - = deg.pdf
public void turnRight(double degrees) {rotationInDegrees + - = deg.pdf
 
Demo creating-physics-game.
Demo creating-physics-game.Demo creating-physics-game.
Demo creating-physics-game.
 
Academy PRO: Unity 3D. Environment
Academy PRO: Unity 3D. EnvironmentAcademy PRO: Unity 3D. Environment
Academy PRO: Unity 3D. Environment
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
 
Sceneform SDK на практиці - UA Mobile 2019
Sceneform SDK на практиці - UA Mobile 2019Sceneform SDK на практиці - UA Mobile 2019
Sceneform SDK на практиці - UA Mobile 2019
 
Sceneform SDK на практиці - UA Mobile 2019
Sceneform SDK на практиці - UA Mobile 2019Sceneform SDK на практиці - UA Mobile 2019
Sceneform SDK на практиці - UA Mobile 2019
 
Game dev 101 part 2
Game dev 101   part 2Game dev 101   part 2
Game dev 101 part 2
 

Más de Jussi Pohjolainen

Más de Jussi Pohjolainen (19)

Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha Platform
 
Intro to PhoneGap
Intro to PhoneGapIntro to PhoneGap
Intro to PhoneGap
 
Quick Intro to JQuery and JQuery Mobile
Quick Intro to JQuery and JQuery MobileQuick Intro to JQuery and JQuery Mobile
Quick Intro to JQuery and JQuery Mobile
 
JavaScript Inheritance
JavaScript InheritanceJavaScript Inheritance
JavaScript Inheritance
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
XAMPP
XAMPPXAMPP
XAMPP
 
Building Web Services
Building Web ServicesBuilding Web Services
Building Web Services
 
CSS
CSSCSS
CSS
 
Extensible Stylesheet Language
Extensible Stylesheet LanguageExtensible Stylesheet Language
Extensible Stylesheet Language
 
About Http Connection
About Http ConnectionAbout Http Connection
About Http Connection
 

Último

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 

Último (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 

Box2D and libGDX

  • 1. Box2D  and  libGDX   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 2. Box2D   •  Free  open  source  2D  physics  simulator  engine   wriEen  in  C++   •  Has  been  used  for  example  in  Angry  Birds,   Tiny  Wings   •  Has  been  ported  to  Java,  Flash,  C#,  JavaScript   •  Programs  that  use  Box2D   – libGDX,  Unity,  iOS  SpriteKit,  GameMaker   Studio  ...  
  • 3. Concepts   •  World   –  CollecNon  of  bodies,  fixtures,  joints  that  interact   •  Body   –  Game  Objects  that  contains  fixtures   –  Dynamic  (spaceship),  StaAc  (ground)  and  KinemaAc   –  Fixture   •  Body  has  Fixture!   •  Density:  Mass  per  square  meter:  bowling  ball  dense,  balloon  not   •  FricAon:  When  sliding  along  something,  amount  of  opposite  force   •  ResAtuAon:  How  bouncy  object  is  (0  =  does  not  bounce,  1  =  very  bouncy)     •  Shape   –  Fixture  has  Shape   –  Polygon  or  Circle,  can  be  mixed   •  Joint   –  Holds  bodies  together.  Several  joints  available.  
  • 4. World   Body   Fixture   Shape   // Create array full of bodies Array<Body> bodies = new Array<Body>(); // Take all bodies from world and put them into array world.getBodies(bodies); // Get shape of first body, it's first fixture and it's shape Shape s = bodies.get(0).getFixtureList().get(0).getShape();
  • 5. Units   •  Box2D  uses  floaAng  points   •  Tuned  for  meter  –  kilogram  –  second  (KMS)   •  OpNmized  so  that  shapes  can  move  between   0.1  –  10  meters   •  It's  tempNng  to  use  pixel  as  units  -­‐>  leads  to   poor  simulaNon  and  weird  behavior   – Keep  moving  objects  between  0.1  –  10  meters!   •  DO  NOT  USE  PIXELS!  DO  NOT!  
  • 6. Units  in  libGDX   •  Window/real  resoluNon  <-­‐>  World  Units  <-­‐>   Box2D  units  (meters)   •  How  to  handle  this?  Just  use  meters  in  World   Units,  so  you  don't  have  to  make  any   conversions   – float width = 640.0f / 100.0f – float height = 400.0f / 100.0f – camera = new OrthographicCamera(); – camera.setToOrtho(false, width, height);
  • 7. CreaNng  a  World   // Create world and set it's gravity! // true => allow body sleeping World world = new World(new Vector2(0, -9.8f), true); // Next steps: create a body to the world  
  • 8. Body  Types   •  Dynamic  Body   – Player  and  other  actors  on  screen   •  StaAc  Body   – Walls,  floors  and  so  on   •  KinemaAc  Body   – Moving  pladorm  in  pladorm  game   – It's  a  staNc  body  that  can  also  move  and  rotate.   When  dynamic  body  collides,  kinemaNc  body   "wins"    
  • 9. Bodies   •  Bodies  are  objects  in  physics  space   – Does  not  hold  texture!  So  it's  not  visible!   •  Hold  properNes  like   – mass,  velocity,  locaNon,  angle   •  Define  size  and  shape  of  the  body  using  a   fixture   •  Shape  can  be  circle  or  polygon  or  a  mixture  of   these!  
  • 10. CreaNng  a  Body   •  To  create  body,  use   –  // Create BodyDef.. –  Body playerBody = world.createBody(BodyDef); •  BodyDef?   –  Type  of  body?  StaNc,  kinemaNc,  dynamic   –  PosiNon   •  Ager  creaNon,  add  a  Fixture  to  the  body   –  Density,  ResNtuNon  (bouncy?),  fricNon  (slippery?),   shape  (circle  or  polygon)   –  playerBody.createFixture(playerFixtureDef);  
  • 11. CreaNng  a  Body   public void createPlayerBody() { // *** 1) DEFINITION OF A BODY *** / // Body Definition BodyDef myBodyDef = new BodyDef(); // It's a body that moves myBodyDef.type = BodyDef.BodyType.DynamicBody; // Initial position is centered up (width = 12.8, height = 7.2) // This position is the CENTER of the shape! myBodyDef.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2); // *** 2) CREATE THE BODY *** / Body playerBody = world.createBody(myBodyDef);
  • 12. // *** 3) FIXTURE FOR THE BODY *** / // Create fixture and add the shape to it FixtureDef playerFixtureDef = new FixtureDef(); // Mass per square meter (kg^m2) playerFixtureDef.density = 1; // How bouncy object? Very bouncy [0,1] playerFixtureDef.restitution = 1.0f; // How slipper object? [0,1] playerFixtureDef.friction = 0.5f; // Create circle shape. CircleShape circleshape = new CircleShape(); circleshape.setRadius(0.1f); // Add the shape to the fixture playerFixtureDef.shape = circleshape; // Add fixture to the body playerBody.createFixture(playerFixtureDef); }
  • 13. About  Rendering   •  Box2D  holds  the  physics,  it's  not  about   rendering   – For  every  render  call,  update  (step)  the  world   •  To  render,  map  some  texture  to  the  posiNon   of  the  playerBody!   •  For  debugging,  use  debugRenderer  
  • 14. Example  About  Rendering   public class Box2DExample extends ApplicationAdapter { private SpriteBatch batch; public static final boolean DEBUG_PHYSICS = true; public static final float WORLD_WIDTH = 6.4f; public static final float WORLD_HEIGHT = 4.0f; private OrthographicCamera camera; private World world; private Box2DDebugRenderer debugRenderer; @Override public void create () { camera = new OrthographicCamera(); camera.setToOrtho(false, WORLD_WIDTH, WORLD_HEIGHT); batch = new SpriteBatch(); world = new World(new Vector2(0f, -9.81f), true); debugRenderer = new Box2DDebugRenderer(); createPlayerBody(); } public void createPlayerBody() { ... } @Override public void render () { batch.setProjectionMatrix(camera.combined); Gdx.gl.glClearColor(1, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); if(DEBUG_PHYSICS) { debugRenderer.render(world, camera.combined); } batch.begin(); // Do some drawing batch.end(); world.step(1/60f, 6, 2); } }
  • 15. Rendering  (Debug)   // Create the renderer (in create...) Box2DDebugRenderer debugRenderer = new Box2DDebugRenderer(true, // draw bodies false, // joints false, // drawAABBs false, // drawInactiveBodies false, // drawVelocities false); // drawContacts public void render() { ... debugRenderer.render(world, camera.combined); world.step(1 / 60f, 6, 2); ... }
  • 16. Update  World:  Stepping   •  To  update  world,  we  need  to  tell  the  world  to  step   // Advance simulation 1/60 of a sec. This should // correspond to framerate in your game float timeStep = 1/60.0f; // How strongly to correct velocity when colliding // More higher, more correct simulation but cost of performance int velocityIterations = 6; // How strongly to correct position when colliding // More higher, more correct simulation but cost of performance int positionIterations = 2; world.step(timeStep, velocityIterations, positionIterations); •  Do  this  at  the  end  of  the  render()  call  
  • 17. Variable  Nmestep   •  If  you  have  following   – world.step(1/60f, 6, 2); •  SimulaNon  can  be  ruined  if  machine  is  not   able  to  run  at  60fps   •  You  could  calculate  the  game  speed  and  add  it   to  stepping   – world.step(framerate, 6, 2); •  Problem  now  is  that  your  game  can  run  very   very  fast  or  very  very  slow    
  • 18. public void render() { ... doPhysicsStep(); } private double accumulator = 0; private double currentTime = TimeUtils.millis() / 1000.0; private void doPhysicsStep() { // We are not using Gdx.graphics.getDeltaTime(), it may not // be accurate enough. // Current time double newTime = TimeUtils.millis() / 1000.0; // How much time since last call? double deltaTime = newTime - currentTime; currentTime = newTime; float TIME_STEP = 1/60f; // If it took ages (> 0.25 => 4 fps) // FIXED Upper limit to prevent going really slow if(deltaTime > 0.25) { deltaTime = 0.25; } accumulator += deltaTime; while (accumulator >= TIME_STEP) { world.step(TIME_STEP, 6, 2); accumulator -= TIME_STEP; } }
  • 19. "Ground"   public void createGround() { // *** 1) DEFINITION OF A BODY *** / // Body Definition BodyDef myBodyDef = new BodyDef(); // This body won't move myBodyDef.type = BodyDef.BodyType.StaticBody; // Initial position is centered up // This position is the CENTER of the shape! myBodyDef.position.set(WORLD_WIDTH / 2, 0.25f); // *** 2) CREATE THE BODY *** / Body groundBody = world.createBody(myBodyDef); // *** 3) FIXTURE FOR THE BODY *** / // Create shape PolygonShape groundBox = new PolygonShape(); // Real width and height is 2 X this! groundBox.setAsBox( WORLD_WIDTH/2 , 0.25f); // Add shape to fixture, 0.0f is density. // Using method createFixture(Shape, density) no need // to create FixtureDef object as on createPlayer! groundBody.createFixture(groundBox, 0.0f); }
  • 20. Draw  texture  to  body  pos!   public void render() { ... batch.draw(texture, playerBody.getPosition().x, playerBody.getPosition.y); }
  • 21. Draw  texture  to  body  pos!   batch.draw(playerTexture, playerBody.getPosition().x - playerRadius, playerBody.getPosition().y - playerRadius, playerRadius, // originX playerRadius, // originY playerRadius * 2, // width playerRadius * 2, // height 1.0f, // scaleX 1.0f, // scaleY playerBody.getTransform().getRotation() * MathUtils.radiansToDegrees, 0, // Start drawing from x = 0 0, // Start drawing from y = 0 playerTexture.getWidth(), // End drawing x playerTexture.getHeight(), // End drawing y false, // flipX false); // flipY
  • 22. Create  Body  and  Add  User  Data   public void createJussi(float x, float y) { BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyType.DynamicBody; bodyDef.position.set(x,y); Body body = world.createBody(bodyDef); PolygonShape dynamicCircle = new PolygonShape(); dynamicCircle.setAsBox(0.5f, 0.5f); FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = dynamicCircle; fixtureDef.density = 1.0f; fixtureDef.friction = 0.1f; fixtureDef.restitution = 0.8f; body.createFixture(fixtureDef); // user data can be anything! any object! body.setUserData(jussiTexture); }
  • 23. Create  Body  and  Add  User  Data   public void render() { ... debugRenderer.render(world, camera.combined); // populate the array with bodies world.getBodies(bodies); // iterate the bodies for (Body body : bodies) { if(body.getUserData() != null && body.getUserData() == jussiTexture) { batch.draw((Texture) body.getUserData(), body.getPosition().x - 0.5f, body.getPosition().y - 0.5f, ... body.getTransform().getRotation() * MathUtils.radiansToDegrees, ... false ); } } doPhysicsStep(); }
  • 25. Forces  and  Impulses   •  To  move  things  around,  you'll  need  to  apply   forces  or  impulses  to  a  body   •  Force   –  Gradually  over  Nme  change  velocity  of  a  body   –  Also  angular  force  available,  torque  (twisNng  strength)   •  Impulse   –  Change  velocity  immediately   •  Of  course  you  can  just  change  the  posiNon  of  a   body  
  • 26. Examples   // gradually accelerate right body.applyForceToCenter(50f, 0, true); // Jump up body.applyLinearImpulse(new Vector2(0f, 20f), body.getWorldCenter(), true);
  • 28. Collision   world.setContactListener(new ContactListener() { @Override public void beginContact(Contact contact) { Body bodyA = contact.getFixtureA().getBody(); Body bodyB = contact.getFixtureB().getBody(); } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } });