顺利移动LibGdx

时间:2016-02-10 09:42:35

标签: java libgdx rendering

我试图做这件事:

当用户按一次键时,精灵在某些像素上平滑移动。但它只是传送"到位。这是代码:

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+"");
                    }
    }

我做错了什么?

2 个答案:

答案 0 :(得分:5)

我将对您的代码进行解构:

while (co < 33) {

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

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

您可以按帧速率* 5增加y位置。因此5 * 0.02 * 33之类的内容正在发生3.3。这没有什么不对,但是使用循环是非常规的。由于做y = 5 * framerate * 33会相同,更容易,更快。

这取决于你想要达到的目的,但基本上“我们”会做这样的事情。

//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就是多么简单。原始pos (0, 0plus 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个纹理将以正确的方式学习。

除此之外,为什么还有一个名为ppos的变量?为什么不只是positionpatientPositionpalaeoanthropologyPosition或“p”代表什么。您只需要在大多数IDE中键入一次,因为intellisense会将其选中。因此,通过明确定义变量,让您和他人的生活更轻松。

答案 1 :(得分:0)

你应该使用Scene2D进行平稳移动。