我试图制作2D汽车侧滚动游戏。我使用轮接头来移动汽车。
这是汽车不动的截图。
Screenshot of car when not moving
当汽车行驶时。你可以看到精灵位置不正确。
Screenshot when the car is moving
这是汽车对象的构造函数。
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(x, y);
//Chassis
PolygonShape chassisShape = new PolygonShape();
chassisShape.setAsBox(width, height);
chassisFixtureDef.shape = chassisShape;
chassis = world.createBody(bodyDef);
// Car Body Sprite
Sprite body = new Sprite(new Texture(Gdx.files.internal("data/body.png")));
body.setSize(5f, 2f);
body.setPosition(0f, 0);
body.setOrigin(body.getWidth() / 2, body.getHeight() / 2);
chassis.setUserData(body);
chassis.createFixture(chassisFixtureDef);
//Left Wheel
CircleShape wheelShape = new CircleShape();
wheelShape.setRadius(height / 1.5f);
wheelFixtureDef.shape = wheelShape;
leftWheel = world.createBody(bodyDef);
//Sprite Test
wheel = new Sprite(new Texture(Gdx.files.internal("data/wheel.png")));
wheel.setSize(1f, 1f);
wheel.setOrigin(wheel.getWidth() / 2, wheel.getHeight() / 2);
leftWheel.setUserData(wheel);
leftWheel.createFixture(wheelFixtureDef);
//Right Wheel
rightWheel = world.createBody(bodyDef);
rightWheel.setUserData(wheel);
rightWheel.createFixture(wheelFixtureDef);
//Left Axis
WheelJointDef def = new WheelJointDef();
def.bodyA = chassis;
def.bodyB = leftWheel;
def.frequencyHz = chassisFixtureDef.density;
def.localAnchorA.set(-width / 2 * 1.7f + wheelShape.getRadius(), -height / 2 * 2.5f);
def.localAxisA.set(Vector2.Y);
def.maxMotorTorque = chassisFixtureDef.density * 30;
leftAxis = (WheelJoint) world.createJoint(def);
def.bodyB = rightWheel;
def.localAnchorA.x *= -1;
rightAxis = (WheelJoint) world.createJoint(def);
以下是在屏幕上绘制与身体相关的精灵的代码。
for (Body body : bodies)
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);
}
很抱歉,如果无法使我的问题变得非常具体或明确。我是Stackoverflow的新手。
刚放入渲染方法[正确]
renderer.render(world, camera.combined);
在gl.clear之后在屏幕上绘制所有内容之后,我正在这样做。 [错误]
答案 0 :(得分:1)
似乎是在渲染后更新物理,因为物理调试的多边形已经比精灵显示的更多。您可以尝试先更新物理,然后绘制您的精灵。
代码/计算本身不应该出错。
如果您已经这样做,可能是因为您的物理模拟更新比渲染循环更频繁。