我有一个游戏JPanel添加到一个框架。 gamePanel(在下面发布)用于每帧渲染移动。公共游戏(){
public Game() {
Dimension dimension = new Dimension(Game.WIDTH, Game.HEIGHT);
setPreferredSize(dimension);
setMaximumSize(dimension);
setMinimumSize(dimension);
setVisible(true);
player = new Player(Game.WIDTH / 2, Game.HEIGHT / 2);
level = new Level("/map/map.png");
spriteSheet = new SpriteSheet("/sprites/sprites.png");
new Texture();
start();
setFocusable(true);I cant seem to get the action to happen.
//other game functions like keybindings.
处理帧速率以及应该对帧进行绘制()的代码是......
@Override
public void run() {
requestFocus();// This does not require the mouse to click frame for it to work
int fps = 0;
double timer = System.currentTimeMillis();
long lastTime = System.nanoTime();
double targetTick = 60.0;
double delta = 0;
double ns = 1000000000 / targetTick;
while (isRunning) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
this.tick();
repaint();//not sure if this is right I just want the frame to update the position of the player and the level
fps++;
delta--;
}
if (System.currentTimeMillis() - timer >= 1000) {
fps = 0;
timer += 1000;
}
}
stop();
}
public synchronized void start() {
System.out.println("start accessed");//this does get accessed
if (isRunning) return;
isRunning = true;
thread = new Thread(this);//UPDATED
thread.start();
}
public synchronized void stop() {
if (!isRunning) return;
isRunning = false;
try {
thread.join();// what does thread join do?
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void tick() {
if (enter) { //enter boolean
System.out.println(enter);
player.tick();
level.tick();
repaint();
revalidate();
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
player.render(g);
level.render(g);
}
基本上是关卡和玩家随着时间的推移而移动。我让它在画布上工作但是从那时起将程序转换为使用JPanel。
感谢您的帮助。