Java游戏,FPS从300下降到1
我的游戏有问题,我找不到问题,我的FPS从300下降到1,每秒降低5到10 FPS,直到它无法玩。 它首先在wave.myFirstGame.Handler.removeObject(Handler.java:31)处给我一个错误,游戏启动但崩溃。但是当我删除了导致这个错误的代码时,游戏可以运行,但是FPS会下降,仍然无法运行Java游戏,FPS从300下降到1,java,runtime-error,lag,2d-games,Java,Runtime Error,Lag,2d Games,我的游戏有问题,我找不到问题,我的FPS从300下降到1,每秒降低5到10 FPS,直到它无法玩。 它首先在wave.myFirstGame.Handler.removeObject(Handler.java:31)处给我一个错误,游戏启动但崩溃。但是当我删除了导致这个错误的代码时,游戏可以运行,但是FPS会下降,仍然无法运行 import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; public c
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
public class BasicEnemy extends GameObject {
private Handler handler;
public BasicEnemy(int x, int y, ID id, Handler handler) {
super(x, y, id);
this.handler = handler;
velX = 5;
velY = 5;
}
public Rectangle getBounds() { //for collision
return new Rectangle(x, y, 16, 16);
}
public void tick() {
x += velX;
y += velY;
if (y <= 0 || y >= Game.HEIGHT - 32)
velY *= -1; // limits of the screen for the enemy
if (x <= 0 || x >= Game.WIDTH - 16)
velX *= -1;
handler.addObject(new Trail(x, y,ID.Trail, Color.red, 16, 16, 0.02f, handler));
}
public void render(Graphics g) {
g.setColor(Color.red);
g.fillRect(x, y, 16, 16);
}
我知道很多代码,但我找不到问题所在,所以如果你有任何建议或想法,最好听听他们。
谢谢大家! 我认为这条线路有可能泄漏:
handler.addObject(新轨迹(x,y,ID.Trail,Color.red,16,16,0.02f,handler))代码>
您正在每个刻度处创建类型为Trail
的新对象。
这可能会导致速度变慢。。后来坠机了
您确定不能重用该对象吗
public void removeObject(GameObject object) {
this.removeObject(object); //this is the error and the game craches after 1 sec, if i remove it, it works but FPS drops
}
在方法->StackOverflowError
应该是:
public void removeObject(GameObject object) {
this.object.remove(object); //this is the error and the game craches after 1 sec, if i remove it, it works but FPS drops
}
此外,在每个勾号中添加一个新的Trail
对象,并且永远不会删除它,因此可能会耗尽内存。尝试在构造函数中添加一次,然后使用getter和setter更改其x
和y
。您没有告诉我们错误是什么,但我怀疑这是堆栈溢出。这是因为您会不断地从自身调用removeObject()
改变
this.removeObject(object);
到
我还建议将LinkedList对象的名称更改为LinkedList对象,因为它是多个对象的集合,这将有助于减少addObject()
和removeObject()中的混淆
函数,其中参数具有相同的名称。这是一些与fps相关的任意代码。您的代码在哪里呈现任何内容?你的主机在哪里?您的列表中有多少个对象?旁注:您可能想了解如何编写“合理的”java代码。例如,您可以将tick方法的主体重写为(GameObject-game:object){game.tick();}
。不需要计数器和临时对象。还有:改进你的命名。使用能说明事物是什么的名称。你知道,就像调用你的列表
游戏对象而不是“对象”。你能看出那会有什么不同吗?!而且你知道:事实上,你在所有地方都使用同一个名字“object”,这是非常糟糕的做法。最后:没有必要在你的问题上都使用粗体字。我们可以在没有您大胆支持的情况下阅读。@GhostCat非常感谢您提供的反馈和信息,非常有帮助。我是一个新手,在网上学到了所有东西,我想每天编写代码,这样我就可以学到尽可能多的东西,并在旅途中获得写作技能。关于如何提高我的写作水平,你有什么建议吗?@AlinMureș一个标准答案:获得罗伯特·马丁的“干净代码”,并仔细研究。并且:在你身边找到有经验的程序员,让他们检查你的代码。或者,在codereview.stackexchange.comOh上发布(工作)代码,永远不会注意到,非常感谢,它现在可以工作了!FPS是稳定的,没有下降。我会在10分钟内接受你的答案,因为我还不能。太早了,haha@Nasso明白了,就是这个;应该是这个。对象。移除(对象);谢谢汉克斯,这就是问题所在。
public void removeObject(GameObject object) {
this.object.remove(object); //this is the error and the game craches after 1 sec, if i remove it, it works but FPS drops
}
this.removeObject(object);
this.object.remove(object);