流畅移动LibGdx

Smooth moving LibGdx

我正在尝试制作这个东西:

当用户按下一个键时,精灵会在某些像素上平滑移动。但它只是 "teleporting" 的位置。这是代码:

int co = 0;
Vector2 ppos=new Vector2(x,y);
    if (Gdx.input.isKeyJustPressed(Keys.A)){
        while (co < 33) {
                        batch.begin();
                        ppos.y += Gdx.graphics.getDeltaTime()*5;
                        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
                        batch.draw(Splayer, ppos.x, ppos.y); //Splayer is a sprite
                        batch.end();
                        co++;
                        out(co+"");
                    }
    }

我做错了什么?

你应该使用 Scene2D 来平滑移动。

我会解构你的代码:

while (co < 33) {

所以这将循环 33 次,因为你有 co = 0 并在每个循环中增加 co。

ppos.y += Gdx.graphics.getDeltaTime()*5;

你将 y 位置增加了你的帧率 * 5。所以像 5 * 0.02 * 33 这样的事情正在发生,这使得 3.3。这没什么问题,但为此使用循环有点不合常规。因为做 y = 5 * framerate * 33 是一样的,更容易也更快。

这取决于你想得到什么,但基本上 "we" 做这样的事情。

//Have position variable
private Vector2 position;
//Have a speed variable
private float speed;
//direction variable
private Vector2 direction;
//have a velocity variable (direction * speed)
private Vector2 velocity;

速度应为direction * speed,然后可以将速度添加到每个帧的位置。假设我们想向上移动。方向将是 (0,1)(方向不应超过 1 的长度,如果超过则对向量进行归一化 direction.nor()。这将确保它的长度为 1,因此相乘将导致相同的速度在任何方向。

direction = new Vector2(0,1);
//an easy way to make it go 45 degree up/right would be
direction = new Vector2(1,1);
direction.nor(); //normalized to 1 long.

//now we can make the velocity

velocity = direction.cpy().scl(speed); //we copy the vector first so we are not changing the direction vector. 
//If you want to have this framerate independent 
velocity = direction.cpy().scl(speed * Gdx.graphics.getDeltatime);

现在我们只需将速度添加到位置。基础数学(1, 1) + (0, 1) = (1 ,2)。是的,这就是 Vector 的简单之处。原始位置 (0, 0)plus direction multiplied by speed+ (0 * 10, 1 * 10) = (0, 10)`。所以要在代码中将速度添加到位置:

position.add(velocity);
batch.draw(textures, position.x, position.y);

这就是我的做法,我觉得这很容易。

你做错的是当你按下 "A" 时在每个游戏循环中生成一个新的 Vector。对于在循环中使用 new 关键字,您应该三思。最好将更改引导或重置它,因为旧的更改会丢失在内存中并需要收集。一个 Vector 不会给你带来麻烦,但是 1 个需要手动处理的 Texture 会给你带来麻烦,学习正确的方法。

除此之外,为什么要有一个名为ppos的变量?为什么不只是 positionpatientPositionpalaeoanthropologyPosition 或 "p" 代表的任何内容。大多数 IDE 您只需要输入一次,因为智能感知会识别它。因此,通过明确定义变量,让您和他人的生活更轻松。