如何用libGDX实现以下效果?

时间:2017-03-05 05:04:02

标签: libgdx

我用libGDX开发游戏。我有一个问题:了解初始坐标和目标坐标,如图所示,如何实现子弹的抛物线效果?实现贝壳的操作。谁能教我?或者告诉我一些教程。 TKS

图片

this answer

1 个答案:

答案 0 :(得分:0)

您需要为您的应用添加一些物理(例如Box2d)。然后你扔掉了#39;具有一定速度和一些方向/角度的佳能球。 物理引擎为你休息。 这里有box2d的教程:https://www.youtube.com/watch?v=vXovY2KTing

非常基本的例子,没有box2d扔东西。对于你的例子,你需要计算正确的权力'目标位置。

public class SampleApp extends ApplicationAdapter
{
    Sprite sprite;
    Vector2 velocity = new Vector2(0, 0);
    Vector2 terminateVelocity = new Vector2(2000, 2000);
    Vector2 friction = new Vector2(200, 300);
    Vector2 position = new Vector2(0, 0);
    Vector2 launchPower = new Vector2(0, 0);
    boolean shotNow;

    @Override
    public void render()
    {
        update(Gdx.graphics.getDeltaTime());
        // ...
        // here render your stuff
    }

    public void shot(float power)
    {
        // Calculate x launch power
        launchPower.x = ((power - sprite.getX() + sprite.getWidth()*0.5f) / 2f) + velocity.x;
        // We want to end our fly at ground
        launchPower.y = ((0 - sprite.getY()) / 2f) + velocity.y;
        // Setup start position
        position.x = sprite.getX();
        position.y = sprite.getY();
        // Add some acc to velocity
        velocity.add(launchPower);
        shotNow = true;
    }

    public void update(float dt)
    {
        if (Gdx.input.justTouched()) {
            shot(900);
        }
        // Very basic sprite movement.
        // For best results you should implement more physics (acceleration etc.)
        if (shotNow && position.y > 0) {
            // Friction/gravity
            velocity.x = MathUtils.clamp(velocity.x - friction.x * dt, -terminateVelocity.x, terminateVelocity.x);
            velocity.y = MathUtils.clamp(velocity.y - friction.y * dt, -terminateVelocity.y, terminateVelocity.y);
            position.add(velocity.x * dt, velocity.y * dt);
            sprite.setPosition(position.x, position.y);
        }
    }
}