Advertisement

JBox2D weird bug

Started by August 13, 2014 04:37 PM
0 comments, last by MatejaS 10 years, 6 months ago

I started using JBox2D in my project today.I made one dynamic and one static body.The dynamic body should fall (due to gravity) until it hits the static body (and bounce).But in my project,it goes into the static body and then stops.Sorry for bad explanation,I attached a screenshot so you can see what I meant.The blue body is static and white is dynamic.

Here's my code:


public class PanelRenderer {
	
	private Keyboard kbd;
	
	private World world=new World(new Vec2(0.0f,9.81f));
	
	private Body body;
	
	private Body gr;
	
	private final float SCALE_FACTOR=30.0f;
	
	private float metersToPixels(float m)
	{
		return m*SCALE_FACTOR;
	}
	private Vec2 metersToPixels(Vec2 v)
	{
		return new Vec2(v.x*SCALE_FACTOR,v.y*SCALE_FACTOR);
	}

	private float pixelsToMeters(float px)
	{
		return px/SCALE_FACTOR;
	}
	private Vec2 pixelsToMeters(Vec2 v)
	{
		return new Vec2(v.x/SCALE_FACTOR,v.y/SCALE_FACTOR);
	}
	
	private Body createBox(float x,float y,BodyType type,float density,float width,float height)
	{
		BodyDef def=new BodyDef();
		def.position.set(pixelsToMeters(new Vec2(x,y)));
		def.type=type;
		Body body=world.createBody(def);
		FixtureDef fDef=new FixtureDef();
		fDef.density=density;
		PolygonShape shape=new PolygonShape();
		shape.setAsBox(pixelsToMeters(width)/2.0f,pixelsToMeters(height)/2.0f);
		fDef.shape=shape;
		body.createFixture(fDef);
		
		return body;
	}
	
	public PanelRenderer(Keyboard kbd)
	{
		this.kbd=kbd;
		body=createBox(0.0f,0.0f,BodyType.DYNAMIC,0.0f,20.0f,20.0f);
		gr=createBox(0.0f,400.0f,BodyType.STATIC,0.0f,100.0f,10.0f);
	}
	
	public void update()
	{
		world.step(1.0f/60.0f,8,3);
	}
	
	
	public void render(Graphics g)
	{	
		Vec2 pos2=metersToPixels(gr.getPosition());
		g.setColor(Color.BLUE);
		g.fillRect((int)pos2.x,(int)pos2.y, 100, 10);
		
		Vec2 pos=metersToPixels(body.getPosition());
		g.setColor(Color.WHITE);
		g.fillRect((int)pos.x, (int)pos.y, 20, 20);
	}
	
}

Thanks,

MatejaS

I have solved the problem :D.

JBox2D's body position is actually the center of mass of the object.

I thought it was top-left corner.

This topic is closed to new replies.

Advertisement