java - 平滑移动 LibGdx

标签 java libgdx rendering

我正在尝试做这个:

当用户按一次键时, Sprite 会在某些像素上平滑移动。但它只是“传送”到了该位置。这是代码:

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

我做错了什么?

最佳答案

我将解构你的代码:

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 是相同的,更容易、更快。

这取决于您想要最终得到什么,但基本上“我们”会做这样的事情。

//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;

速度应该是方向 * 速度,然后可以将速度添加到每个帧的位置。假设我们想升职。方向将是 (0,1) (方向永远不应该超过 1 的长度,如果超过,则标准化 vector 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, 0)加上方向乘以速度+ (0 * 10, 1 * 10) = (0, 10)`。因此,要在代码中添加速度到位置:

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

这就是我的做法,我发现这很简单。

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

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

关于java - 平滑移动 LibGdx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35311536/

相关文章:

java - 如何在 Node js/Java 中捕获网络调用?

java - 如何让每个图 block 对象都使用空数组列表启动,以便稍后添加内容?

java - 获取经验证据以显示 float 和 double 之间内部存储差异的问题

Java 洪水填充问题

java - Java Swing 组件 onUpdate 渲染错误

Java贪吃蛇游戏——重画特定的drawString()方法

java - 线相交多边形不起作用

java - Libgdx |盒子2d |从 PolygonShape 创建圆

google-chrome - Chrome 显示奇怪的颜色问题

c++ - 渲染二维元素的引用(圆形、圆角矩形、模糊~)