LibGdx Box2d collison not matching up with sprite - java

I am making a game as a project for a college class. when my main character (the tree) hits the ground, it stops short of the ground
screenshot 1
and when the player lands on the little platform that gap is even bigger
screenshot 2
my code for creating the body of the character and and ground is this
public static Body createBody(int x, int y, float width, float height, boolean isStatic){
Body body;
BodyDef def = new BodyDef();
if(isStatic){
def.type = BodyDef.BodyType.StaticBody;
}
else {
def.type = BodyDef.BodyType.DynamicBody;
}
def.position.set(x / PPM , y / PPM);
// returns a World object
body = GlobalWorld.getInstance().createBody(def);
PolygonShape shape = new PolygonShape();
shape.setAsBox(width / 2 / PPM, height / 2 / PPM);
body.createFixture(shape, 1.0f);
shape.dispose();
return body;
}
The code for the ground is in it's own class
public class Material {
private Texture image;
private Body body;
private Sprite sprite;
public Material(Texture t, int x, int y, int w, int h){
image = t;
sprite = new Sprite(t);
body = BoxBuilder.createBody(x, y, w, h, true);
body.setUserData("Ground");
}
public void draw(){
// returns a SpriteBatch
SpriteBatch batch = GlobalBatch.getInstance();
sprite.setPosition(body.getPosition().x * PPM, body.getPosition().y * PPM);
batch.begin();
sprite.draw(batch);
batch.end();
}
public void dispose(){
image.dispose();
}
}
the code for drawing the ground
public void draw(){
for(Material m : worldObjects){
m.draw();
}
}
my code for drawing the character
public void create(){
// do stuff
// global vars
body = createBody(0, 480, 313, 260, false);
texture = new Texture("tree.PNG");
sprite = new Sprite(texture);
// do stuff
}
public void render(){
// do stuff
sprite.setPosition(body.getPosition().x*PPM, body.getPosition().y*PPM);
batch.begin()
sprite.draw(batch)
batch.end()
// do stuff
}
and PPM(Pixel per Meter) is
public static final float PPM = 32;
I don't know what is the problem here, I want the character to land on the ground, not land above it. So if someone could tell me what's causing this or point me to a good tutorial for learning more about box2d I'd appreciate it.

When we create body with PolygonShape then body is at the center of that Polygon so when draw with body position it starts drawing from center of PolygonShape so we need to draw at left bottom corner.
In Material class
replace
sprite.setPosition(body.getPosition().x * PPM, body.getPosition().y * PPM);
with
sprite.setPosition(body.getPosition().x*PPM-sprite.getWidth()/2,body.getPosition().y-sprite.getHeight()/2);
sprite.setRotation(body.getAngle()*MathUtils.radDeg);
And for Character draw also change
sprite.setPosition(body.getPosition().x*PPM, body.getPosition().y*PPM);
with
sprite.setPosition(body.getPosition().x*PPM-sprite.getWidth()/2, body.getPosition().y*PPM-sprite.getHeight()/2);
sprite.setRotation(body.getAngle()*MathUtils.radDeg);
As I see in your code you're not setting size of Sprite in Material class as well as for Character so set width and height.
In Material Class
sprite = new Sprite(t);
sprite.setSize(w,h);
And for Character
body = createBody(0, 480, 313, 260, false);
texture = new Texture("tree.PNG");
sprite = new Sprite(texture);
sprite.setSize(313,260);

Related

LibGDX float with camera position causing black lines with Tiled map

I am creating a top-down shooter game, and whenever I move the camera, or zoom, black likes appear like a grid
I am using Tiled to create the map, and I have the camera following my centered box2d body. I have found that making the camera position equal the position of the box2d body with an int cast results in the black lines disappearing like this:
The problem though, is that because I have the game scaled down, the player will move for a second or two and then when the player reaches the next whole number on either axis, the camera snaps to the player, which is not what I want for the game as it's jarring. The player's movement is granular, but, while rounded, the camera's is not. I do not know if this is a problem with my tile sheet or if it's something I can fix by altering some code. I have tried all different kinds of combinations of padding, and values of spacing and margins. So ultimately, how can I have the camera match the player's position smoothly and not cause the black lines? I'd greatly appreciate any help or recommendations. Thank you in advance!
Where I am type casting the player's float position to an int in game class:
public void cameraUpdate(float delta) {
//timeStep = 60 times a second, velocity iterations = 6, position iterations = 2
world.step(1/60f, 6, 2); //tells game how many times per second for Box2d to make its calculations
cam.position.x = (int)playerOne.b2body.getPosition().x;
cam.position.y = (int)playerOne.b2body.getPosition().y;
cam.update();
}
Majority of player class:
public class PlayerOne extends Sprite implements Disposable{
public World world; // world player will live in
public Body b2body; //creates body for player
private BodyDef bdef = new BodyDef();
private float speed = 1f;
private boolean running;
TextureAtlas textureAtlas;
Sprite sprite;
TextureRegion textureRegion;
private Sound runningSound;
public PlayerOne(World world) {
this.world = world;
definePlayer();
textureAtlas = new TextureAtlas(Gdx.files.internal("sprites/TDPlayer.atlas"));
textureRegion = textureAtlas.findRegion("TDPlayer");
sprite =new Sprite(new Texture("sprites/TDPlayer.png"));
sprite.setOrigin((sprite.getWidth() / 2) / DunGun.PPM, (float) ((sprite.getHeight() / 2) / DunGun.PPM - .08));
runningSound = Gdx.audio.newSound(Gdx.files.internal("sound effects/running.mp3"));
}
public void definePlayer() {
//define player body
bdef.position.set(750 / DunGun.PPM, 400 / DunGun.PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
//create body in the world
b2body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
CircleShape shape = new CircleShape();
shape.setRadius(12 / DunGun.PPM);
fdef.shape = shape;
b2body.createFixture(fdef);
}
public void renderSprite(SpriteBatch batch) {
float posX = b2body.getPosition().x;
float posY = b2body.getPosition().y;
float posX2 = (float) (posX - .14);
float posY2 = (float) (posY - .1);
sprite.setSize(32 / DunGun.PPM, 32 / DunGun.PPM);
sprite.setPosition(posX2, posY2);
float mouseX = Level1.mouse_position.x; //grabs cam.unproject x vector value
float mouseY = Level1.mouse_position.y; //grabs cam.unproject y vector value
float angle = MathUtils.atan2(mouseY - getY(), mouseX - getX()) * MathUtils.radDeg; //find the distance between mouse and player
angle = angle - 90; //makes it a full 360 degrees
if (angle < 0) {
angle += 360 ;
}
float angle2 = MathUtils.atan2(mouseY - getY(), mouseX - getX()); //get distance between mouse and player in radians
b2body.setTransform(b2body.getPosition().x, b2body.getPosition().y, angle2); //sets the position of the body to the position of the body and implements rotation
sprite.setRotation(angle); //rotates sprite
sprite.draw(batch); //draws sprite
}
public void handleInput(float delta) {
setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2 + (5 / DunGun.PPM));
this.b2body.setLinearVelocity(0, 0);
if(Gdx.input.isKeyPressed(Input.Keys.W)){
this.b2body.setLinearVelocity(0f, speed);
}if(Gdx.input.isKeyPressed(Input.Keys.S)){
this.b2body.setLinearVelocity(0f, -speed);
}if(Gdx.input.isKeyPressed(Input.Keys.A)){
this.b2body.setLinearVelocity(-speed, 0f);
}if(Gdx.input.isKeyPressed(Input.Keys.D)){
this.b2body.setLinearVelocity(speed, 0f);
}if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.A)){
this.b2body.setLinearVelocity(-speed, speed);
}if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.D)){
this.b2body.setLinearVelocity(speed, speed);
}
if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.A)){
this.b2body.setLinearVelocity(-speed, -speed );
}if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.D)){
this.b2body.setLinearVelocity(speed, -speed);
}
Where I declare the pixels per meter scale:
public class DunGun extends Game{
public SpriteBatch batch;
//Virtual Screen size and Box2D Scale(Pixels Per Meter)
public static final int V_WIDTH = 1500;
public static final int V_HEIGHT = 800;
public static final float PPM = 100; //Pixels Per Meter
Game render and resize methods:
#Override
public void render(float delta) {
cameraUpdate(delta);
playerOne.handleInput(delta);
//clears screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) {
cam.zoom -= .01;
}
if (Gdx.input.isButtonPressed(Input.Buttons.RIGHT)) {
cam.zoom += .01;
}
mapRenderer.render();
b2dr.render(world, cam.combined); //renders the Box2d world
mapRenderer.setView(cam);
//render our game map
//mapRenderer.render(); // renders map
//mapRenderer.render(layerBackround); //renders layer in Tiled that p1 covers
game.batch.setProjectionMatrix(cam.combined); //keeps player sprite from doing weird out of sync movement
mouse_position.set(Gdx.input.getX(), Gdx.input.getY(), 0);
cam.unproject(mouse_position); //gets mouse coordinates within viewport
game.batch.begin(); //starts sprite spriteBatch
playerOne.renderSprite(game.batch);
game.batch.end(); //starts sprite spriteBatch
//mapRenderer.render(layerAfterBackground); //renders layer of Tiled that hides p1
}
#Override
public void resize(int width, int height) {
viewport.update(width, height, true); //updates the viewport camera
}
I solved it by fiddling around with the padding of the tilesets in GDX Texture Packer. I added 5 pixels of padding around the 32x32 tiles. I set the margins to 2, and spacing to 4 in Tiled. I had tried a lot of different combinations of padding/spacing/margins that didn't work which made me think it was a coding problem, but those settings worked, and I didn't have to round the floats.

Polygon position for collision detection won't update? or Collide?

I'm using polygons for a method of collision detection. I have a rock, the moves in a certain direction.
When I run the application, the polygon renders into a perfect rectangle where the rock is when it is started.
Yet, it doesn't move with the rock.
public Polygon box;
private int width;
public int height;
public float [] vertices;
public Rock (float x, float y, int width, int height) {
this.width = width;
this.height = height;
position = new Vector2(x, y);
velocity = new Vector2(20, 0);
vertices = new float[] {position.x, position.y, position.x+width, position.y, position.x+width, position.y+height,
position.x, position.y+height};
box = new Polygon ();
box.setOrigin(width/2, height/2);
}
public void RockMove (float delta) {
position.add(velocity.cpy().scl(delta));
box.setVertices(vertices);
box.setPosition(position.x, position.y);
}
sprite batch for rock
public void render (float delta) {
batch.begin();
batch.enableBlending();
batch.draw(rock, rock.GetX(), rock.GetY(), rock.GetWidth(), rock.GetHeight());
batch.disableBlending();
batch.end();
}
And this is some code from a render class
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
shapeRenderer.setColor(Color.RED);
shapeRenderer.polygon(Rock.vertices);
shapeRenderer.end();
Again, the polygon shows up perfectly, but doesn't move. I don't have any errors.
Edit: I defined the vertices again in the Rock Move method, and now they move with the rock.
public void RockMove (float delta) {
position.add(velocity.cpy().scl(delta));
box.setVertices(vertices);
box.setPosition(position.x, position.y);
vertices = new float[] {position.x, position.y, position.x+width,
position.y, position.x+width, position.y+height,
position.x, position.y+height};
}
But for some reason, the collision detection won't work.
Don't define vertices again in update instead of you should use transformedVertices of Polygon.
Polygon polygon=new Polygon();
float transformed[] = polygon.getTransformedVertices();
TransformedVertices is the vertices of the polygon after scaling, rotation, and positional translations have been applied.

Libgdx/Java ShadowMap and Framebuffer update using Cameras

im working on a little rpg game and today i tried to add shadows.
I saw this tutorial here which is good :)
Pixel Perfect Shader
So following problem :
Test example from the tutorial site, works fine. Theres one cam and the shadows are on the right place.
As soon i use Orthographic cameras from my player sprite, the shadow isnt there where it should be and when im moving the shadow moves with me, he is on the same spot on the display screen but in the world the shadow is moving _/ that looks so :
The SpriteSheet should cast shadows ... but they are on the wrong place :/
Here i didnt moved :
It is very dark, because of the day/night cycle ...
And here i moved a little bit to left :
I dont know why it wont work ... im giving the Orthographic camera out of my main class to the shadow class. Or did i miss something ? :/
My code should be fine, but if anyone wanna see it here is some code :
public class LightSystemShader {
private int lightSize = 500;
private float upScale = 1f; //for example; try lightSize=128, upScale=1.5f
SpriteBatch batch;
OrthographicCamera cam;
BitmapFont font;
FPSLogger fps;
TextureRegion shadowMap1D; //1 dimensional shadow map
TextureRegion occluders; //occluder map
FrameBuffer shadowMapFBO;
FrameBuffer occludersFBO;
Texture casterSprites;
Texture enmyAnimation;
Texture light;
ShaderProgram shadowMapShader, shadowRenderShader;
Array<Light> lights = new Array<Light>();
boolean additive = true;
boolean softShadows = true;
float xKoord = 600;
public static ShaderProgram createShader(String vert, String frag) {
ShaderProgram prog = new ShaderProgram(vert, frag);
if (!prog.isCompiled())
throw new GdxRuntimeException("could not compile shader: " + prog.getLog());
if (prog.getLog().length() != 0)
Gdx.app.log("GpuShadows", prog.getLog());
return prog;
}
public LightSystemShader() {
batch = new SpriteBatch();
ShaderProgram.pedantic = false;
//read vertex pass-through shader
final String VERT_SRC = Gdx.files.internal("data/pass.vert").readString();
// renders occluders to 1D shadow map
shadowMapShader = createShader(VERT_SRC, Gdx.files.internal("data/shadowMap.frag").readString());
// samples 1D shadow map to create the blurred soft shadow
shadowRenderShader = createShader(VERT_SRC, Gdx.files.internal("data/shadowRender.frag").readString());
//the occluders
casterSprites = new Texture("data/cat4.png");
//
enmyAnimation = new Texture("EnemyAnimations/BugIdleStand.png");
//the light sprite
light = new Texture("data/light.png");
cam = new OrthographicCamera(0,0);
cam.setToOrtho(false);
updateMaps();
font = new BitmapFont();
Gdx.input.setInputProcessor(new InputAdapter() {
public boolean touchDown(int x, int y, int pointer, int button) {
float mx = x;
float my = Gdx.graphics.getHeight() - y;
lights.add(new Light(mx, my, randomColor()));
return true;
}
public boolean keyDown(int key) {
if (key==Keys.SPACE){
clearLights();
return true;
} else if (key==Keys.A){
additive = !additive;
return true;
} else if (key==Keys.S){
softShadows = !softShadows;
return true;
}
return false;
}
});
clearLights();
}
public void renderLightSystemShader(OrthographicCamera screenCam){
screenCam = new OrthographicCamera(0,0);
screenCam.setToOrtho(false);
Gdx.gl.glClearColor(0,0,0,0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
float mx = Gdx.input.getX();
float my = Gdx.graphics.getHeight() - Gdx.input.getY();
if (additive)
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
for (int i=0; i<lights.size; i++) {
Light o = lights.get(i);
if (i==lights.size-1) {
o.x = mx;
o.y = my;
}
renderLight(o, screenCam);
}
if (additive)
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
//STEP 4. render sprites in full colour
batch.setProjectionMatrix(screenCam.combined);
batch.begin();
batch.setShader(null); //default shader
drawShaderBatch(batch);
//DEBUG RENDERING -- show occluder map and 1D shadow map
/*batch.setColor(Color.BLACK);
batch.draw(occluders, Gdx.graphics.getWidth()-lightSize, 0);
batch.setColor(Color.WHITE);
batch.draw(shadowMap1D, Gdx.graphics.getWidth()-lightSize, lightSize+5);
//DEBUG RENDERING -- show light
batch.draw(light, mx-light.getWidth()/2f, my-light.getHeight()/2f); //mouse
batch.draw(light, Gdx.graphics.getWidth()-lightSize/2f-light.getWidth()/2f, lightSize/2f-light.getHeight()/2f);
*/
//draw FPS
batch.end();
System.out.println(Gdx.graphics.getFramesPerSecond());
}
// draw Lights
void renderLight(Light o, OrthographicCamera screenCam) {
float mx = o.x;
float my = o.y;
screenCam = new OrthographicCamera(0,0);
screenCam.setToOrtho(false);
//STEP 1. render light region to occluder FBO
//bind the occluder FBO
occludersFBO.begin();
//clear the FBO
Gdx.gl.glClearColor(0f,0f,0f,0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//set the orthographic camera to the size of our FBO
screenCam.setToOrtho(false, occludersFBO.getWidth(), occludersFBO.getHeight());
//translate camera so that light is in the center
screenCam.translate(mx - lightSize/2f, my - lightSize/2f);
//update camera matrices
screenCam.update();
//set up our batch for the occluder pass
batch.setProjectionMatrix(screenCam.combined);
batch.setShader(null); //use default shader
batch.begin();
// ... draw any sprites that will cast shadows here ... //
batch.draw(casterSprites, 0, 0);
batch.draw(enmyAnimation,xKoord,600,300,100);
//end the batch before unbinding the FBO
batch.end();
//unbind the FBO
occludersFBO.end();
//STEP 2. build a 1D shadow map from occlude FBO
//bind shadow map
shadowMapFBO.begin();
//clear it
Gdx.gl.glClearColor(0f,0f,0f,0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//set our shadow map shader
batch.setShader(shadowMapShader);
batch.begin();
shadowMapShader.setUniformf("resolution", lightSize, lightSize);
shadowMapShader.setUniformf("upScale", upScale);
//reset our projection matrix to the FBO size
screenCam.setToOrtho(false, shadowMapFBO.getWidth(), shadowMapFBO.getHeight());
batch.setProjectionMatrix(screenCam.combined);
//draw the occluders texture to our 1D shadow map FBO
batch.draw(occluders.getTexture(), 0, 0, lightSize, shadowMapFBO.getHeight());
//flush batch
batch.end();
//unbind shadow map FBO
shadowMapFBO.end();
//STEP 3. render the blurred shadows
//reset projection matrix to screen
screenCam.setToOrtho(false);
batch.setProjectionMatrix(screenCam.combined);
//set the shader which actually draws the light/shadow
batch.setShader(shadowRenderShader);
batch.begin();
shadowRenderShader.setUniformf("resolution", lightSize, lightSize);
shadowRenderShader.setUniformf("softShadows", softShadows ? 1f : 0f);
//set color to light
batch.setColor(o.color);
float finalSize = lightSize * upScale;
//draw centered on light position
batch.draw(shadowMap1D.getTexture(), mx-finalSize/2f, my-finalSize/2f, finalSize, finalSize);
//flush the batch before swapping shaders
batch.end();
//reset color
batch.setColor(Color.WHITE);
//xKoord+=1;
}
void clearLights() {
lights.clear();
lights.add(new Light(Gdx.input.getX(), Gdx.graphics.getHeight()-Gdx.input.getY(), Color.WHITE));
}
static Color randomColor() {
float intensity = (float)Math.random() * 0.5f + 0.5f;
return new Color((float)Math.random(), (float)Math.random(), (float)Math.random(), intensity);
}
void drawShaderBatch(SpriteBatch batch){
batch.draw(casterSprites, 0, 0);
batch.draw(enmyAnimation,600,600,300,100);
}
void updateMaps(){
occludersFBO = new FrameBuffer(Format.RGBA8888, lightSize, lightSize, false);
occluders = new TextureRegion(occludersFBO.getColorBufferTexture());
occluders.flip(false, true);
//our 1D shadow map, lightSize x 1 pixels, no depth
shadowMapFBO = new FrameBuffer(Format.RGBA8888, lightSize, 1, false);
Texture shadowMapTex = shadowMapFBO.getColorBufferTexture();
//use linear filtering and repeat wrap mode when sampling
shadowMapTex.setFilter(TextureFilter.Linear, TextureFilter.Linear);
shadowMapTex.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
//for debugging only; in order to render the 1D shadow map FBO to screen
shadowMap1D = new TextureRegion(shadowMapTex);
shadowMap1D.flip(false, true);
}
public void doDispose(){
batch.dispose();
font.dispose();
shadowMapFBO.dispose();
shadowMapShader.dispose();
shadowRenderShader.dispose();
casterSprites.dispose();
enmyAnimation.dispose();
light.dispose();
occludersFBO.dispose();
}
}
Found it out myself ^^ i forgot to add this to void renderLights :
cam.position.set(positionX,positionY, 0);

How to make camera same speed as player

I'm making an endless runner on LibGDX with Box2d. I want to make the camera and player move at the same speed so while everything's fine, the player is in the center of the screen. I don't want it to just always make the player the center though, since I want the player to be left behind by the camera if the player gets stuck (ex. behind a crate). With that, I was thinking that I could translate the camera with the same default velocity that the player has. Doesn't work though. Help?
render() (with the camera update):
dx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//stage.getCamera().translate(Constants.DEFAULT_VELOCITY / Constants.PIXELS_TO_BOX, 0, 0);
//the commented function call above was what I was thinking; doesnt work
stage.getCamera().position.x = player.getX();
batcher.begin();
batcher.draw(AssetLoader.background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batcher.end();
stage.draw();
batcher.begin();
debugRenderer.render(gameWorld.getWorld(), debugMatrix);
batcher.end();
part of Player:
public Player(Texture texture, float x, float y, World world) {
this.texture = texture;
setWidth(texture.getWidth()); //pixels
setHeight(texture.getHeight()); //pixels
setPosition((x + getWidth()/2), y + (getHeight()/2)); //pixels
setName("player");
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(x / Constants.PIXELS_TO_BOX, y / Constants.PIXELS_TO_BOX); //meters
body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape();
shape.setAsBox(texture.getWidth()/2 / Constants.PIXELS_TO_BOX , texture.getHeight()/2 / Constants.PIXELS_TO_BOX); //meters
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 0.0f;
body.createFixture(fixtureDef);
body.setFixedRotation(true);
shape.dispose();
body.setUserData(this);
}
#Override
public void act(float delta) {
body.setLinearVelocity(new Vector2(Constants.DEFAULT_VELOCITY, body.getLinearVelocity().y));
//what I use to set velocity
if (hasJumped) {
jump();
hasJumped = false;
Gdx.app.log("player", "jumped");
}
}

Body moving without any force applied? (Box2d)

So I am making a game in box 2d. In one part I need a ball which has a constant bounce height. I set the ball's restitution to 1 and am applying no force on it whatsoever (except gravity of course). Now this ball, on every bounce, bounces a bit higher everytime till it goes out of the top edge of the screen. What is wrong with this code?
public class Ball implements ApplicationListener {
World world ;
Box2DDebugRenderer debugRenderer;
OrthographicCamera camera;
static final float BOX_STEP=1/60f;
static final int BOX_VELOCITY_ITERATIONS=8;
static final int BOX_POSITION_ITERATIONS=3;
static final float WORLD_TO_BOX=0.01f;
static final float BOX_WORLD_TO=100f;
Rectangle ball;
Body body;
/* (non-Javadoc)
* #see com.badlogic.gdx.ApplicationListener#create()
*/
#Override
public void create() {
world = new World(new Vector2(0, -10), true);
camera = new OrthographicCamera();
camera.viewportHeight = 480;
camera.viewportWidth = 800;
camera.position.set(camera.viewportWidth * .5f, camera.viewportHeight * .5f, 0f);
camera.update();
//Ground body
BodyDef groundBodyDef =new BodyDef();
groundBodyDef.position.set(new Vector2(0, 10 * WORLD_TO_BOX));
Body groundBody = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
float w = (camera.viewportWidth * 2) * WORLD_TO_BOX;
float h = 10.0f * WORLD_TO_BOX;
groundBox.setAsBox(w,h);
groundBody.createFixture(groundBox, 0.0f);
String a="gb";
groundBody.setUserData(a);
//Dynamic Body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
float posX = (camera.viewportWidth / 8) * WORLD_TO_BOX;
float posY = (camera.viewportHeight / 2) * WORLD_TO_BOX;
bodyDef.position.set(posX, posY);
body = world.createBody(bodyDef);
// create a Rectangle to logically represent the ball
CircleShape dynamicCircle = new CircleShape();
dynamicCircle.setRadius(1f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = dynamicCircle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution =1f;
body.createFixture(fixtureDef);
debugRenderer = new Box2DDebugRenderer();
}
#Override
public void dispose() {
}
#Override
public void render() {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
debugProjection.set(camera.combined);
debugProjection.scl(BOX_WORLD_TO);
debugRenderer.render(world, debugProjection);
world.step(BOX_STEP, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
This may be caused by numerical instability. Repeatedly calculating positions of your ball inevitably introduces tiny numerical errors (because a float can only hold a limited number of digits). These may grow and add up from iteration to iteration, bounce to bounce.
You can try using restitution 0.9999999 or something. But chances are that there is no restitution value which gives desired results.
Try to actively compensate for the numerical instability e.g. by controlling the ball's position and/or velocity in situations in which you can calculate values non-iteratively. (I do not know Box2D. Maybe when the ball hits the ground you can reset its speed or something.)
Ok I solved it by setting the restitution to 0 and applying an upward force of 5N on each contact. As halfbit said, the problem is that because box2d uses float, the position calculations are not precise which causes minor changes in height on every bounce.
If I have done the math right for the calculations, your sphere has a radius of 1m, and your box as dimensions of 16m x 0.1m.
In Box2d, everything needs to be on the scale of 0.1m to 10m. The reason your bodies may be numerically unstable is because the ratio of the width to height is greater than the normal sizes of objects. While you may get some stability by changing the restitution, I think you will always be on the "hairy edge" with these dimensions.
Try changing the dimensions of your objects so the width is 8 and the height is 0.1.

Categories

Resources