即时速度变化LibGDX

时间:2016-08-09 13:58:53

标签: java android libgdx

我是Java和Android的新手。我最近一直在尝试使用LibGDX为Android创建游戏。该游戏的一个方面涉及一个人从屏幕的一侧移动到另一侧(水平地)。这是我的代码:`

public class Man {
    private static final int SP = 10;
    private static final int NSP = -10;
    private Vector3 position;
    private Vector3 velocity;
    private Texture man;

    public Man(int x, int y){
        position = new Vector3(x, y, 0);
        velocity = new Vector3(0, 0, 0);
        man = new Texture ("person.png"); 

    }

    public void update(float dt){
        if (position.x > 2560) {
            velocity.add(NSP, 0, 0);
        }
        else {
            velocity.add(SP, 0, 0);
        }
        velocity.add(SP, 0, 0);
        velocity.scl(dt);
        position.add(velocity.x, 0, 0);
        velocity.scl(1/dt);
    }

    public Texture getTexture() {
        return man;
    }

    public Vector3 getPosition() {
        return position;
    }

    public void dispose(){
        man.dispose();
    }

}

我还不习惯弄清楚这样的问题。当我运行此代码时,此人从屏幕的一侧(左侧)经过屏幕的另一侧(右侧,不在视野中)。在一两秒之后,该人回到视野中(从右侧)并且到达屏幕的另一侧(到左侧,留在视野中)。然后重复这个过程。此外,当这个人开始移动时,他需要一秒钟来全速前进。我试图删除if else语句并创建2个具有不同速度的人(一个带有正面,一个带负面)来创造一个幻觉,即男人立即改变速度(通过移除一个人并产生另一个人),但我还没有能够做到这一点。

我想知道如何让这个人立即达到全速,立即在屏幕的另一侧改变速度,然后循环继续这个过程。任何帮助将非常感激。 感谢。

1 个答案:

答案 0 :(得分:1)

浏览代码并思考逻辑。

您遵循if-else语句并始终将SP添加到速度。如此有效,您可以将该数学与if-else结合使用,从而得到以下结果:

    if (position.x > 2560) {
        velocity.add(0, 0, 0);
    }
    else {
        velocity.add(2 * SP, 0, 0);
    }
    velocity.scl(dt);
    position.add(velocity.x, 0, 0);
    velocity.scl(1/dt);

或更简单:

    if (position.x <= 2560) {
        velocity.add(2 * SP, 0, 0);
    }
    velocity.scl(dt);
    position.add(velocity.x, 0, 0);
    velocity.scl(1/dt);

所以你总是在每一帧加速2 * SP,除非你不在屏幕上,在这种情况下你的速度会停止增加,但是你仍然会在屏幕外向右缩放。

如果您想立即更改速度,则需要将其设置为特定值,而不是向其添加内容。我还建议不要缩放和取消缩放矢量,因为这可能会引入舍入错误。以下是如何让您的角色从屏幕的左侧和右侧进行乒乓。

public void update(float dt){
    if (velocity.x == 0) 
        velocity.x = SP; //first frame setup

    //only change the velocity if character is off screen, otherwise leave it alone
    if (position.x > 2560)
        velocity.x = NSP;
    else if (position.x < 0 - texture.getWidth())
        velocity.x = SP;

    position.add(velocity.x * dt, 0, 0);
}

注意,我使用texture.getWidth()作为占位符,无论你的角色是多少。实际上,在播放器类中加载诸如Texture之类的资源是不好的做法。您正在将资产与游戏逻辑混合在一起,这是一种容易出错并且难以维护的代码配方。最好使用资产管理器类来加载和存储您的所有资产。您的角色的绘制方法可以将资产管理器作为参数,并从那里选择其资产参考。例如:

public void draw (SpriteBatch batch, MyAssets assets){
    TextureRegion region = assets.getRegion("man"); //imaginary assets class--implementation up to you
    batch.draw(region, x, y);
}