Jadi masalah ini telah bersaudara selama beberapa hari sekarang. Pertama, apa perbedaan antara katakanlah Body.getWorldCenter () dan Body.getPosition (). Saya mendengar bahwa WorldCenter mungkin ada hubungannya dengan pusat gravitasi atau sesuatu.
Kedua, Ketika saya membuat Tubuh Box2D untuk sprite Tubuh selalu di sudut kiri bawah. Saya memeriksanya dengan mencetak Rectangle 1 pixel di sekitar box.getWorldCenter (). Dari apa yang saya pahami Tubuh seharusnya berada di tengah Sprite dan kotak pembatasnya harus membungkus Sprite, benar?
Ini gambar yang saya maksud (Sprite is Red, Body Blue):
Ini beberapa kode:
Pembuat Tubuh:
public static Body createBoxBody( final World pPhysicsWorld, final BodyType pBodyType,
final FixtureDef pFixtureDef, Sprite pSprite ) {
float pRotation = 0;
float pCenterX = pSprite.getX() + pSprite.getWidth() / 2;
float pCenterY = pSprite.getY() + pSprite.getHeight() / 2;
float pWidth = pSprite.getWidth();
float pHeight = pSprite.getHeight();
final BodyDef boxBodyDef = new BodyDef();
boxBodyDef.type = pBodyType;
//boxBodyDef.position.x = pCenterX / Constants.PIXEL_METER_RATIO;
//boxBodyDef.position.y = pCenterY / Constants.PIXEL_METER_RATIO;
boxBodyDef.position.x = pSprite.getX() / Constants.PIXEL_METER_RATIO;
boxBodyDef.position.y = pSprite.getY() / Constants.PIXEL_METER_RATIO;
Vector2 v = new Vector2( boxBodyDef.position.x * Constants.PIXEL_METER_RATIO, boxBodyDef.position.y * Constants.PIXEL_METER_RATIO );
Gdx.app.log("@Physics", "createBoxBody():: Box Position: " + v);
// Temporary Box shape of the Body
final PolygonShape boxPoly = new PolygonShape();
final float halfWidth = pWidth * 0.5f / Constants.PIXEL_METER_RATIO;
final float halfHeight = pHeight * 0.5f / Constants.PIXEL_METER_RATIO;
boxPoly.setAsBox( halfWidth, halfHeight ); // set the anchor point to be the center of the sprite
pFixtureDef.shape = boxPoly;
final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);
Gdx.app.log("@Physics", "createBoxBody():: Box Center: " + boxBody.getPosition().mul(Constants.PIXEL_METER_RATIO));
boxBody.createFixture(pFixtureDef);
boxBody.setTransform( boxBody.getWorldCenter(), MathUtils.degreesToRadians * pRotation );
boxPoly.dispose();
return boxBody;
}
Membuat Sprite:
public Car( Texture texture, float pX, float pY, World world ) {
super( "Car" );
mSprite = new Sprite( texture );
mSprite.setSize( mSprite.getWidth() / 6, mSprite.getHeight() / 6 );
mSprite.setPosition( pX, pY );
mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2);
FixtureDef carFixtureDef = new FixtureDef();
// Set the Fixture's properties, like friction, using the car's shape
carFixtureDef.restitution = 1f;
carFixtureDef.friction = 1f;
carFixtureDef.density = 1f; // needed to rotate body using applyTorque
mBody = Physics.createBoxBody( world, BodyDef.BodyType.DynamicBody, carFixtureDef, mSprite );
}