我正在编写游戏,并且我在上面使用带box2D库的libGDX。我有一个问题。如您所知,CircleShape .setPosition()有一个用于定位形状的函数,我正在使用它在该形状中设置精灵,如下图所示:
在这里我正在创建该形状,如您所见,有一个函数“ setPosition”可以根据我的精灵来适应形状:
CircleShape ballShape = new CircleShape();
ballShape.setPosition(new Vector2(-1.5f, 0f)); //Here i set the position
//of the shape
ballShape.setRadius(1.5f);
// fixture definition
fixtureDef.shape = ballShape;
fixtureDef.density = 0f;
fixtureDef.friction = 0;
fixtureDef.restitution = 0;
playerCircle = world.createBody(bodyDef);
playerCircle.createFixture(fixtureDef);
ballShape.dispose();
在这里,我根据CircleShape绘制了精灵:
batch.begin();
boxSprite = new Sprite(new Texture(
"C:/Users/HOME/Desktop/videoGameGit/videogameGit/box2DExample-android/assets/data/sprites/player/ak47stand.png"));
boxSprite.setSize(5.5f, 5.5f);
boxSprite.setOrigin(boxSprite.getWidth() / 2, boxSprite.getHeight() / 2);
playerCircle.setUserData(boxSprite);
world.getBodies(tmpBodies);
for (Body body : tmpBodies)
if (body.getUserData() != null && body.getUserData() instanceof Sprite) {
Sprite sprite = (Sprite) body.getUserData();
sprite.setPosition((body.getPosition().x - sprite.getWidth() / 2),
(body.getPosition().y - sprite.getHeight() / 2));
sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
sprite.draw(batch);
}
batch.end();
此时一切正常,但是当我想使用某个polygonShape .setAsBox绘制对象时,没有可以使用的函数.setPosition。
这对我来说是个问题,因为我必须根据子画面设置形状的位置,如您在另一幅图中所看到的。精灵的位置不正确:
由于PolygonShape中没有类似于setPosition的函数,因此这是我将多边形Shape创建为Box的代码的一部分:
bodyDef.type = BodyType.DynamicBody;
PolygonShape chair = new PolygonShape();
chair.setAsBox(1.3f, 1.4f, new Vector2(x, y), 0);
fixtureDef.shape = chair;
fixtureDef.density = 10f;
fixtureDef.friction = 10;
fixtureDef.restitution = 0f;
body = world.createBody(bodyDef);
body.createFixture(fixtureDef);
body.setAngularDamping(5);
body.setLinearDamping(8);
chair.dispose();
我在这里绘制它:
batch.begin();
sprite.setSize(5.5f, 5.5f);
sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
body.setUserData(sprite);
world.getBodies(tmpBodies);
for (Body body : tmpBodies)
if (body.getUserData() != null && body.getUserData() instanceof Sprite) {
Sprite sprite = (Sprite) body.getUserData();
sprite.setPosition((body.getPosition().x - sprite.getWidth() / 2),
(body.getPosition().y - sprite.getHeight() / 2));
sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
sprite.draw(batch);
}
batch.end();
我的问题是,有一种方法可以正确地将多角形与精灵配合?我希望有人能帮助我。
谢谢!。