【问题标题】:What is best way to move an Object in libGDX在 libGDX 中移动对象的最佳方法是什么
【发布时间】:2020-01-29 17:38:41
【问题描述】:

我刚刚编写了一个简单的应用程序来测试通过用户提供的输入来移动图形纹理。屏幕中间有一个圆圈png,如果用户触摸它,圆圈将跟随用户的手指。 这是代码:

private int HEIGHT, WIDTH;
private Circle circle;
private final int RADIUS = 256;
private boolean circleTouched, firstClick;
private SpriteBatch batch;
private Texture b1;

@Override
public void create()
{
    WIDTH = Gdx.graphics.getWidth();
    HEIGHT = Gdx.graphics.getHeight();
    circleTouched = false;
    firstClick = true;
    batch = new SpriteBatch();
    b1 = new Texture("b1.png");
    circle = new Circle(WIDTH / 2, HEIGHT / 2, RADIUS);
}

@Override
public void render()
{
    //Logic
    if (Gdx.input.isTouched())
    {
        if (circleTouched)
        {
            circle.x += Gdx.input.getDeltaX();
            circle.y += Gdx.input.getDeltaY();
        }
        else if (isCircleTouched(Gdx.input.getX(), Gdx.input.getY(), circle) && firstClick)
        {
            circleTouched = true;
        }
        else
        {
            firstClick = false;
        }
    }
    else
    {
        circleTouched = false;
        firstClick = true;
    }

    //Drawing
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw(b1, circle.x - circle.radius, HEIGHT - circle.y - circle.radius);
    batch.end();
}

@Override
public void dispose()
{
    super.dispose();
}

private boolean isCircleTouched(int x, int y, Circle c)
{
    return ((x - c.x) * (x - c.x) + (y - c.y) * (y - c.y)) <= (c.radius * c.radius);
}
  1. 这是移动对象的好方法吗(如果我有 15 个像这个应用程序这样的对象,性能仍然会很好吗?)
  2. 是否可以不从左下角而是从左上角使用函数绘制?每次画画都要减去高度。
  3. 我的 png 是 512x512 如何设置尺寸以绘制具有给定尺寸的纹理?

编辑 1. firstClick 可以替换为 Gdx.input.justTouched()

【问题讨论】:

    标签: java libgdx game-physics


    【解决方案1】:
    1. 我找不到那么多的 15 个对象,尤其是当您只使用 2d 纹理和一些简单的数学运算时。但是,当您的代码库增长时,您应该考虑重构它并将逻辑移至专用类。
    2. draw 函数始终使用左下角。但是您可以使用可以获取原点坐标的Sprite 类:https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/graphics/g2d/Sprite.html
    3. 如果您不想为此尝试Sprite 类,您也可以使用Texture.getWidthgetHeight 方法:https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/graphics/Texture.html#getWidth--

    在构建libGdx 代码时,我总是发现Ashley 很有帮助:https://github.com/libgdx/ashley/wiki/How-to-use-Ashley

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2018-09-26
      • 2013-03-26
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多