我会解构你的代码:
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;
速度应该是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)。是的,这就是向量的简单程度。原始位置 (0, 0)plus direction multiplied by speed+ (0 * 10, 1 * 10) = (0, 10)`。所以要在代码中添加速度到位置:
position.add(velocity);
batch.draw(textures, position.x, position.y);
这就是我的做法,我觉得这很容易。
当您按“A”时,您做错的是在每个游戏循环中生成一个新向量。您应该三思而后行在循环中使用 new 关键字。最好将更改矢量或重置它,因为旧的更改将丢失在内存中并需要收集。一个 Vector 不会给您带来麻烦,但需要手动处理的 1 个 Texture 会,以正确的方式学习。
除此之外,为什么有一个名为ppos 的变量?为什么不只是position 或patientPosition 或palaeoanthropologyPosition 或任何“p”代表的东西。您只需要在大多数 IDE 中键入一次,因为智能感知会接收到它。因此,通过明确定义变量,让您和他人的生活更轻松。