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

时间:2018-11-18 11:28:30

标签: java libgdx box2d

我正在尝试制作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);
}

} enter image description here

1 个答案:

答案 0 :(得分:0)

来自docs for Sprite

  

旋转(浮动度)
  设置精灵相对于当前旋转的旋转角度。

,并来自docs for b2Body

  

void b2Body :: SetAngularVelocity(float32 omega)
  设置角速度。
  参数
  Ω新的角速度(弧度/秒)。

因此,一种方法期望弧度,而另一种方法期望度。您必须转换您的价值。

两个弧度的度数为b2body.setAngularVelocity(-1 * 180.f / PI);

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

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

此外,这些方法还具有不同的作用:设置速度,设置相对旋转角度。即使在固定参数之后,如果您获得相同的结果,也只能靠运气,只有当您每隔一帧调用这些并且帧持续时间与box2d角速度完全匹配(意味着它每帧精确地旋转Ω)时,这种情况才会发生。

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

setRotation(b2body.getAngle() * 180.f / PI);
相关问题