Libgdx - 如何在scene2d中的正确位置绘制填充矩形?

Ale*_*drs 12 drawing rectangles shapes game-engine libgdx

我正在使用scene2d.这是我的代码:

    group.addActor(new Actor() {
        @Override
        public Actor hit(float arg0, float arg1) {return null;}
        @Override
        public void draw(SpriteBatch batch, float arg1) {
            batch.end();
            shapeRenderer.begin(ShapeType.FilledRectangle);
            shapeRenderer.setColor(Color.RED);
            shapeRenderer.filledRect(0, 0, 300, 20);
            shapeRenderer.end();
            batch.begin();
        }
    });
Run Code Online (Sandbox Code Playgroud)

问题是它相对于屏幕绘制了这个矩形(x = 0,y = 0),但我需要它相对于我的绘制.但是,如果我绘制其他实体:

batch.draw(texture, 0, 0, width, height);
Run Code Online (Sandbox Code Playgroud)

它正确地绘制了(x = 0,y = 0)相对于我的组(从组的左下角0,0像素).

任何建议如何在scene2d中实现形状绘制?有人可以解释为什么这两个调用的工作方式不同吗?

Rod*_*yde 19

ShapeRenderer有自己的变换矩阵和投影矩阵.它们与scene2d Stage使用的SpriteBatch中的那些分开.如果更新ShapeRenderer的矩阵以匹配scene2d在调用Actor.draw()时使用的矩阵,那么您应该得到所需的结果.


Jul*_*ien 13

正如Rod Hyde所提到的,ShapeRenderer有自己的变换矩阵和投影矩阵.所以你必须首先获得SpriteBatch的投影矩阵.我不确定是否有一种优雅的方式来做,我这样做:

public class myActor extends Actor{

 private ShapeRenderer shapeRenderer;
 static private boolean projectionMatrixSet;

 public myActor(){
     shapeRenderer = new ShapeRenderer();
     projectionMatrixSet = false;
 }

 @Override
   public void draw(SpriteBatch batch, float alpha){
       batch.end();
       if(!projectionMatrixSet){
           shapeRenderer.setProjectionMatrix(batch.getProjectionMatrix());
       }
       shapeRenderer.begin(ShapeType.Filled);
       shapeRenderer.setColor(Color.RED);
       shapeRenderer.rect(0, 0, 50, 50);
       shapeRenderer.end();
       batch.begin();

   }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ndr 6

对我来说最好的解决方案.因为当您使用ShapeRenderer时它不会对移动/缩放相机做出反应.

public class Rectangle extends Actor {

    private Texture texture;

    public Rectangle(float x, float y, float width, float height, Color color) {
        createTexture((int)width, (int)height, color);

        setX(x);
        setY(y);
        setWidth(width);
        setHeight(height);
    }

    private void createTexture(int width, int height, Color color) {
        Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
        pixmap.setColor(color);
        pixmap.fillRectangle(0, 0, width, height);
        texture = new Texture(pixmap);
        pixmap.dispose();
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        Color color = getColor();
        batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
        batch.draw(texture, getX(), getY(), getWidth(), getHeight());
    }
}
Run Code Online (Sandbox Code Playgroud)