首页 > 解决方案 > LibGDX 的 Box2D 在设置角速度时具有奇怪的旋转行为

问题描述

我从 PolygonShape 创建了一个简单的动态主体,并将其渲染为由 PolygonSpriteBatch 渲染的 PolygonSprite。渲染效果很好,但物理效果不行。速度引起的平移效果很好,但是当我设置角速度或施加扭矩时,身体也会在其原点旋转的同时围绕一个点“旋转”。问题不在于起源,因为在调试时我注意到身体的位置也在变化。唯一的旋转不应该使身体平移,对吧?

这是它的旋转方式。我只设置了角速度。

旋转行为

我在调试时检查过的线速度总是等于0,但是位置发生了变化(这没有任何意义),所以它应该不是由错误的旋转原点引起的渲染问题。

这是我用多边形创建身体的地方。

public DrawableBody createFullBody(float[] vertices, Body body, Texture tex, Vector2 coord){
    //in our example: vertices = new float[]{0.0f, 0.0f, 0.0f, 1f, 1f, 1f, 1f, 0.0f};
    DrawableBody out = new DrawableBody(); //a class that contains Body and PolygonSprite
    ShortArray indices = triangulate(vertices); //uses EarClippingTriangulator
    
    PolygonShape shape = new PolygonShape();
    shape.set(vertices);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1f;
    fixtureDef.restitution = 0.9f;
    
    Fixture fixture = body.createFixture(fixtureDef);
    
    shape.dispose(); //this is useless now, so we can dispose it.
    
    PolygonRegion region = new PolygonRegion(new TextureRegion(tex), vertices, indices.toArray());
    PolygonSprite sprite = new PolygonSprite(region);
    body.setTransform(coord, 0);
    sprite.setPosition(coord.x, coord.y);
    
    out.body = body;
    out.poly = sprite;
    
    return out;
}

这就是我渲染正方形的方式:

public void render(PolygonSpriteBatch batch, float delta){
    Vector2 pos = body.getPosition(); //this changes even if velocity is zero?!?
    Vector2 size = model.robotSize; //this is Vector2(0.1f, 0.1f)
    
    float angle = body.getAngle();
    
    d_body.poly.setPosition(pos.x - size.x / 2.0f, pos.y - size.y / 2.0f);
    d_body.poly.setSize(size.x, size.y);
    d_body.poly.setOrigin(size.x / 2.0f, size.y / 2.0f);
    d_body.poly.setRotation(angle);
    
    batch.draw(d_body.poly.getRegion(), 
            d_body.poly.getX(),       d_body.poly.getY(),
            d_body.poly.getOriginX(), d_body.poly.getOriginY(), 
            d_body.poly.getWidth(),   d_body.poly.getHeight(), 
            1.0f, 1.0f,
            d_body.poly.getRotation());
}

我现在在这个问题上苦苦挣扎了两天,所以任何帮助都将不胜感激。

标签: javalibgdxgame-physicsbox2d

解决方案


推荐阅读