我正在尝试编写一个简单的flappy bird游戏作为Java Applet。我遇到的问题是,图形的响应非常迟钝,通常需要5-10秒才能在按键后做出响应。而且,只有按键一定的次数,大约6或7次,它才会响应。我不认为这是我的电脑的问题,因为我是在一个高规格的MacBook专业版(8 GB内存,i5处理器)上运行它。下面是我使用的两个主要类:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
//The main class I use to run the game
public class Flap extends Applet implements Runnable, KeyListener
{
final int WIDTH = 700, HEIGHT = 500;
Thread thread;
Bird b;
boolean beenPressed = false;
public void init()
{
this.resize(WIDTH, HEIGHT);
this.addKeyListener(this);
b = new Bird();
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g)
{
g.setColor(Color.CYAN);
g.fillRect(0, 0, WIDTH, HEIGHT - 100);
g.setColor(Color.green);
g.fillRect(0, 400, WIDTH, HEIGHT);
b.draw(g);
}
public void update(Graphics g)
{
paint(g);
}
@Override
public void run()
{
for(;;)
{
//Pillar upPillar = new Pillar()
b.move();
repaint();
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_UP)
{
if(!beenPressed)
{
b.setUp(true);
}
beenPressed = true;
}
else
{
b.setDown(true);
}
}
@Override
public void keyReleased(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_UP)
{
beenPressed = false;
b.setUp(false);
}
else
{
b.setDown(false);
}
}
@Override
public void keyTyped(KeyEvent arg0)
{
}
}
import java.awt.Color;
import java.awt.Graphics;
//The Bird class, which has the methods for the player to move
public class Bird
{
int x, y, yvel;
boolean goingUp, goingDown;
public Bird()
{
x = 200;
y = 200;
}
public void draw(Graphics g)
{
g.setColor(Color.yellow);
g.fillRect(x, y, 60, 25);
}
public void move()
{
if(goingUp)
{
yvel -= 50;
}
else if(goingDown)
{
yvel += 50;
}
y += yvel;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setUp(boolean b)
{
goingUp = b;
}
public void setDown(boolean b)
{
goingDown = b;
}
}它还没有完成,但在这个阶段,我认为鸟至少应该在移动。
发布于 2018-02-02 08:12:27
图形并不慢,更新之间的时间太长了。它基本上允许在更新周期发生之前按下和释放键。
我会将Thread.sleep(500);简化为更像Thread.sleep(10);的东西,并将移动增量更改为更像...
public void move()
{
if(goingUp)
{
yvel -= 1;
}
else if(goingDown)
{
yvel += 1;
}
y += yvel;
}作为一个起点。
建议...
使用applet,这是个坏主意。Applet已被弃用,是一项已死的技术。Applet也不是双缓冲的,所以你可能会以一些可怕的闪光结束。KeyListener以有问题(无响应)而闻名,虽然它是使用AWT时的唯一解决方案,但当使用Swing时,ket bindings API是更好的解决方案
我建议的第一件事是先了解一下如何使用JPanel作为基础组件,然后再了解一下Performing Custom Painting和Painting in Swing,以便更好地理解绘画的工作原理
如果你“真的”需要高性能(或者只是想更好地控制绘制过程),你也应该看看BufferStrategy and BufferCapabilities
我还建议你看看JavaFX,它有更好的API来处理这类事情
https://stackoverflow.com/questions/48573682
复制相似问题