Java 更新画布时如何避免使用bufferstrategy闪烁
我正在用Java编写一个platformer游戏。一切正常,没有更大的问题,除了Java 更新画布时如何避免使用bufferstrategy闪烁,java,graphics,awt,java-canvas,Java,Graphics,Awt,Java Canvas,我正在用Java编写一个platformer游戏。一切正常,没有更大的问题,除了画布更新时屏幕上的闪烁 我将大致解释我的游戏“引擎”是如何工作的: 在我的主要方法中,我有一个循环,每秒重复30次: while (play) { Date delay_time = new Date(); delay_time.setTime(delay_time.getTime() + (int) (1000*(1.0/FPS))); // Here is all the game st
画布更新时屏幕上的闪烁
我将大致解释我的游戏“引擎”是如何工作的:
在我的主要方法中,我有一个循环,每秒重复30次:
while (play) {
Date delay_time = new Date();
delay_time.setTime(delay_time.getTime() + (int) (1000*(1.0/FPS)));
// Here is all the game stuff, like the motion of the player,
// function calling, etc.
Graphics g = can.getGraphics();
can.update(g);
while(new Date().before(delay_time)) {
}
}
我的FPS变量是一个当前设置为30的静态final int
。
所以我每秒更新画布30次
Play是一个布尔值,它控制游戏是否仍在玩,或者玩家是否死亡
Can
是我的类MyCanvas.java
的一个实例。
paint()方法的代码如下所示:
if (Main.play) {
//NOW
//Draw the now Level Caption
//SIZE: 240
g2.setFont(new Font("Bank Gothic", Font.PLAIN, 240));
g2.setColor(new Color(Math.abs(bg.getRed() - 30), Math.abs(bg.getGreen() - 30), Math.abs(bg.getBlue() - 30)));
g2.drawString("LEVEL " + Main.lvl, 80, 80 + 300 - Main.groundY);
//Draw the ground
g2.setColor(haba);
g2.fillRect(0, Main.screenSize.height - Main.groundY, Main.screenSize.width, Main.groundY);
//Draw the level
g2.setColor(haba);
for (int i = 0; i < Main.LVLWIDTH; i++) {
for (int j = 0; j < Main.LVLHEIGHT; j++) {
if (Main.level[i][j] == '1') {
g2.fillRect(i*(Main.BLOCK_X), (j - Main.LVLHEIGHT)*(Main.BLOCK_Y) + Main.screenSize.height - Main.groundY, Main.BLOCK_X, Main.BLOCK_Y);
}
}
//More drawing stuff...
}
if(Main.play){
//现在
//绘制现在水平的标题
//尺码:240
g2.setFont(新字体(“银行哥特式”,Font.PLAIN,240));
setColor(新颜色(Math.abs(bg.getRed()-30)、Math.abs(bg.getGreen()-30)、Math.abs(bg.getBlue()-30));
g2.抽绳(“标高”+Main.lvl,80,80+300-Main.groundY);
//开门见山
g2.setColor(haba);
g2.fillRect(0,Main.screenSize.height-Main.groundY,Main.screenSize.width,Main.groundY);
//划一
g2.setColor(haba);
对于(int i=0;i
所以,正如你所看到的,我更新了很多-每秒30次。这导致了我的游戏(在全屏模式下玩)的问题一直闪烁。如何解决这个问题?Bufferstrategy是正确的方法吗?如果是,我应该怎么做?你能解释Bufferstrategy,或者提供一些有很好的教程或解释的链接,这些都是技术性的和非初学者友好的吗?那太好了。Bufferstrategy类解决了我的问题。在这里是一个很好的链接,有一个很好的示例说明如何使用它:
AWT组件不是双缓冲的,Swing组件是。你应该是Sun GETCGRAPH,这不是绘画是如何完成的!你应该重写适当的Price方法。如果想对绘画过程进行绝对控制,我只考虑使用BuffeldDebug,这就排除了使用任何类型的Swing组件的原因。我不知道这是否是一个问题,但你需要注意的是限制Swing组件在默认情况下是双缓冲的。我已经做了两个示例,一个基于组件(因此实体是实际组件),它能够以25帧/秒的速度为5000个单独的元素设置动画,另一个获得10000多个绘制对象(通过覆盖JPanel的paintComponent)以25fps的速度运行,没有太多问题。只需说yr代码中的另一个问题是强制延迟循环。Thread.sleep将使循环线程进入睡眠状态,使用0%的CPU!允许其他线程更好地运行。您已尝试查看