繁体   English   中英

如何使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);
}

} 在此处输入图片说明

Sprite文档中

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

以及来自b2Body文档

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

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

以度为单位的弧度: b2body.setAngularVelocity(-1 * 180.f / PI);

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM