我正在尝试用Java克隆鸡侵略者,游戏的特色之一就是背景的移动。当我在网上搜索时,大多数教程都针对玩家移动背景的情况应该随它一起移动。他们全都使用了我在代码中未使用过的paint()
方法,并且真的不知道在哪里使用。这里是包含我的游戏循环并进行渲染的类:< / p>
package ir.farzinnasiri.display;
import ir.farzinnasiri.state.StateMachine;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
public class Display extends Canvas implements Runnable {
//setting the size
private static final int WIDTH = 1200,HEIGHT = 800;
//the game loop stuff
private boolean running;
private Thread thread;
private int fps;
public static StateMachine state;
private static BufferedImage backGround;
public static int getWIDTH() {
return WIDTH;
}
public static int getHEIGHT() {
return HEIGHT;
}
public Display(){
this.setSize(WIDTH,HEIGHT);
this.setFocusable(true);
state = new StateMachine(this);
state.setState((byte)0);
//setting the background
URL url = this.getClass().getResource("/ir/farzinnasiri/images/gameBG.PNG");
try{
backGround = ImageIO.read(url);
}catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void start(){
if(running){
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop(){
if(!running){
return;
}
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
long timer = System.currentTimeMillis();
long lastLoopTime = System.nanoTime();
final int Target_fps = 100;
/*we need 1/fps to determine the time for each loop,for 60fps this is approximately 16ms
* if all the updates take place under 16ms than we have a steady fps!
*
* */
final long Optimal_Time = 1_000_000_000 /Target_fps;
int frames = 0;
//setting buffer strategy
createBufferStrategy(3);
BufferStrategy bs = getBufferStrategy();
while (running){
long now = System.nanoTime();
long updateLength = now-lastLoopTime;
lastLoopTime = now;
//to not jump and run smooth
double elapsed = updateLength/((double) Optimal_Time);
//each loop adds one frame
frames++;
//check if one second has passed or not
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
fps = frames;
frames = 0;
System.out.println(fps);
}
render(bs);
update(elapsed);
//this part controls the program if it gets very fast
try {
Thread.sleep(Math.abs((lastLoopTime-System.nanoTime())+Optimal_Time)/1_000_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void render(BufferStrategy bs){
do {
do {
Graphics2D g2d = (Graphics2D) bs.getDrawGraphics();
g2d.drawImage(backGround,0,0,getWIDTH(),getHEIGHT(),null);
state.draw(g2d);
g2d.dispose();
} while (bs.contentsRestored());
bs.show();
}while (bs.contentsLost());
}
public void update(double elapsed){
//game updates here
state.update(elapsed);
}
}
目前,我有一艘太空飞船,可以围绕框架移动它。如您所见,我只是从Google下载了space
背景并使用了它。我真的还不够移动背景,以至于太空船似乎在移动。我是游戏编程和Java的新手,所以我对其中的一些帮助或提示非常感激,这个网站和网络上的答案(就我搜索的内容)对我来说不是很有用。