如何让 b2box 主体和精灵以相同的速度旋转?

How to get b2box body and a sprite to rotate at same speed?

我正在尝试制作 2D 游戏,但我一直坚持让 box2D 的主体和 textureRegion 以相同的速度旋转。我的 tetxureRegion 以比 box2D 的主体更快的速度旋转。我认为问题可能来自 "b2body.setAngularVelocity(-1)" 和 "rotate(-1)"。请有人帮助我....谢谢

public class VanishableBLock extends Sprite {

private World world;
private GameScreen screen;
public Body b2body;
public Vector2 velocity;
private float stateTime;
private TextureRegion picture;
private Rectangle rectangle;

public VanishableBLock(GameScreen screen, Rectangle rectangle) {
    this.rectangle = rectangle;
    this.world = screen.getWorld();
    this.screen = screen;
    setPosition((rectangle.getX()+rectangle.getWidth()/2) / MavisAdventure.PPM, (rectangle.getY() +rectangle.getHeight()/2)/ MavisAdventure.PPM);
    setOrigin(rectangle.getWidth()/2/ MavisAdventure.PPM,rectangle.getHeight()/2/ MavisAdventure.PPM);
    this.rectangle.height = rectangle.getHeight();
    this.rectangle.width = rectangle.getWidth();
    createVanishableBLock();
    velocity = new Vector2(0, 0.08f);
    picture = new TextureRegion(screen.getAtlas().findRegion("big_mario"), 80, 0, 16, 32);
    stateTime = 0;
    setRegion(picture);
    setBounds(getX(), getY(), rectangle.getWidth() / MavisAdventure.PPM, rectangle.getHeight() / MavisAdventure.PPM);
}
public void createVanishableBLock()
{
    BodyDef bdef = new BodyDef();
    bdef.position.set(getX(),getY());
    bdef.type = BodyDef.BodyType.DynamicBody;
    b2body = world.createBody(bdef);
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(rectangle.getWidth()/2/MavisAdventure.PPM, rectangle.getHeight()/2/MavisAdventure.PPM);
    fdef.shape = shape;
    fdef.density = 1000;
    b2body.createFixture(fdef).setUserData(this);
}

public void update(float dt)
{
    stateTime +=dt;

    b2body.setAngularVelocity(-1);
    rotate(-1);             //these 2 cannot rotate at same speed

    b2body.setLinearVelocity(velocity );
    setPosition(b2body.getPosition().x - getWidth()/2, b2body.getPosition().y - getHeight()/2);
    setRegion(picture);
}
public void draw(Batch batch)
{
        super.draw(batch);
}

}

来自docs for Sprite

rotate(float degrees)
Sets the sprite's rotation in degrees relative to the current rotation.

和来自 docs for b2Body

void b2Body::SetAngularVelocity(float32 omega)
Set the angular velocity.
Parameters
omega the new angular velocity in radians/second.

所以一种方法需要弧度,一种方法需要度数。你必须转换你的价值。

弧度到度数:b2body.setAngularVelocity(-1 * 180.f / PI);

或度数转弧度:rotate(-1 * PI / 180.f);

其中 PI 是保存 π 值的最终静态值。

除此之外,这些方法还做不同的事情:一种设置速度,一种设置相对旋转角度。即使在固定参数之后,如果你得到相同的结果也只是运气,这只有在你每一帧都调用这些并且帧持续时间与 box2d angular 速度完全匹配时才会发生(这意味着它每帧都精确地旋转 omega ).

我建议将 b2Body 对象的实际角度复制到精灵中,而不是让物理引擎和渲染引擎都计算旋转。物理引擎应该有权控制对象的位置和旋转,而渲染器应该只渲染。像这样:

setRotation(b2body.getAngle() * 180.f / PI);