Advertisement
dermetfan

Box2D draw Animations

Oct 3rd, 2013
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. // in show method:
  2. Sprite sprite = new Sprite(animation.getKeyFrame(0)); // creates it with the first frame, not important
  3. sprite.setSize(shape.getRadius() * 2, shape.getRadius() * 2); // set the size to the shape size (it's a CircleShape, don't just use the radius for other shapes!)
  4. sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2); // recalculate the origin
  5.  
  6. ballBody.setUserData(new Object[] {sprite, animation}); // not really the best way to store the things. better make a class for them
  7.  
  8. // in render method:
  9. animationTime += delta; // accumulate animation state time
  10.  
  11. batch.begin();
  12. for(Body body : tmpBodies)
  13.     if(body.getUserData() instanceof Object[]) {
  14.         // get the Sprite and Animation from the Object array
  15.         Sprite sprite = (Sprite) ((Object[]) body.getUserData())[0];
  16.         Animation animation = (Animation) ((Object[]) body.getUserData())[1];
  17.  
  18.         sprite.setPosition(body.getPosition().x - sprite.getWidth() / 2, body.getPosition().y - sprite.getHeight() / 2);
  19.         sprite.setRotation(body.getAngle() * MathUtils.radDeg);
  20.  
  21.         sprite.setRegion(animation.getKeyFrame(animationTime)); // update the sprite's region with the frame from the animation (does not influence position or size)
  22.  
  23.         sprite.draw(batch);
  24.     }
  25. batch.end();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement