gpt4 book ai didi

java - 即时速度变化 LibGDX

转载 作者:行者123 更新时间:2023-12-01 09:36:33 25 4
gpt4 key购买 nike

我是 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 个具有不同速度的人(一个为正,一个为负),以造成该人立即改变速度的错觉(通过删除一个人并产生另一个人),但我还没有能够做到这一点。

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

最佳答案

浏览您的代码并思考逻辑。

遵循 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,除非你在屏幕之外,在这种情况下你的速度停止增加,但你仍然向右变焦,离开屏幕。

如果你想立即改变你的速度,你需要将其设置为一个特定的值,而不是添加一些东西。我还建议不要缩放和取消缩放 vector ,因为这可能会开始引入舍入误差。以下是如何让你的角色从屏幕的左侧和右侧打乒乓球。

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() 作为占位符来表示字符的宽度。实际上,在玩家类中加载诸如纹理之类的 Assets 是一种不好的做法。您将 Assets 与游戏逻辑混合在一起,这导致代码容易出现错误且难以维护。最好使用 Assets 管理器类来加载和存储所有 Assets 。您的角色的绘制方法可以将资源管理器作为参数,并从那里选择其资源引用。例如:

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

关于java - 即时速度变化 LibGDX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38852870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com