Box2D Circle works but not pentagon Polygon?

I honestly have no idea why, but this code I’m using to create a Polygon Shape doesn’t seem to work. I’m trying to create a regular pentagon given the centre and radius. Circle and Box shapes work.

Here’s the code:

Circle, which works:

Body createCircle(float centreX, float centreY, float radius, BodyType bodyType) {
		BodyDef bodyDef = new BodyDef();
		bodyDef.type = bodyType;
		bodyDef.position.set(centreX, centreY);

		Body body = world.createBody(bodyDef);

		CircleShape circle = new CircleShape();
		circle.setRadius(radius);

		FixtureDef fixtureDef = new FixtureDef();
		fixtureDef.shape = circle;
		fixtureDef.density = 0.5f;
		fixtureDef.friction = 0.4f;
		fixtureDef.restitution = 1f;

		body.createFixture(fixtureDef);

		circle.dispose();
		
		return body;
	}
	

Pentagon, doesn’t work:


	Body createPentagon(float centreX, float centreY, float radius, BodyType bodyType) {
		BodyDef bodyDef = new BodyDef();
		bodyDef.type = bodyType;
		bodyDef.position.set(centreX, centreY);
		
		Body body = world.createBody(bodyDef);
		
		PolygonShape shape = new PolygonShape();
		Vector2[] vertices = new Vector2[5];
		
		for(int i=0; i<=4; i++) {
			vertices[i] = new Vector2(centreX + (float) (radius*Math.cos(i*72)), (float) (centreY + radius*Math.sin(i*72)));
		}
		
		shape.set(vertices);
		
		FixtureDef fixtureDef = new FixtureDef();
		fixtureDef.shape = shape;
		fixtureDef.density = 0.5f;
		fixtureDef.friction = 0.4f;
		fixtureDef.restitution = 1f;

		body.createFixture(fixtureDef);
		
		shape.dispose();
		
		return body;
	}

Any ideas? Is it the maths I’m using wrong?

Correct me if I’m wrong but doesn’t Math.sin use radians? Instead of doing Math.sin(i * 72) would Math.sin(Math.toRadians(i * 72)) work?

Good point, I’ve corrected that but the pentagons still aren’t coming up properly

If you seek help, you have to be a tad more descriptive than ‘it doesn’t quite work’ :wink:

Well, there are no errors, the Fixture just isn’t being created. Not sure how else I can describe the problem.

Edit: Instead of trying to fix this problem, it would also help if someone told me how to create a pentagon fixture given the centre and radius.

Your way is the way I would do it and I see no problems. Are you sure there isn’t an issue with how you are rendering it? As a point of interest, the one thing I can think of different between a box and a pentagon is the pentagon has an odd number of vertices whereas the box has an even number. The same (probably) goes for the circle. So maybe try a hexagon and see what happens there.

The coordinates of each vertice of the fixture are local coordinates, so you should not add (centerX, centerY) to them, as you already set the position of your body to (centerX, centerY).

Thank you very much, that fixed it :smiley: