我目前正在制作游戏并遇到问题,我正在使用key listener
内置的光滑而且(正如您可能已经猜到的那样)X和Y不断变化,我是使用Buffered Writer
,当我保存X和Y时,它保存初始值150 public int X = 150,Y = 150;
,当它真正设置为坐标时。我不确定发生了什么,如果有人能提供帮助那将是非常感谢。
这是一些代码:
保存课程:
public class saveGame {
BufferedWriter bw;
Player p = new Player();
public void save() {
try {
bw = new BufferedWriter(new FileWriter("saves/saveTest.txt"));
//add save things
bw.write("X: " + p.X);
bw.newLine();
bw.write("Y: " + p.Y);
bw.close();
} catch (IOException e) {e.printStackTrace();}
}
}
Player(p。)Class:
public class Player {
int health;
public int X = 150;
public int Y = 150;
public int saveX;
public int saveY;
}
Play Class:
public class Play extends BasicGameState {
int camX;
int camY;
int WORLD_SIZE_X = 100000;
int WORLD_SIZE_Y = 100000;
int VIEWPORT_SIZE_Y = 768;
int VIEWPORT_SIZE_X = 1024;
int offsetMaxX = WORLD_SIZE_X - VIEWPORT_SIZE_X;
int offsetMaxY = WORLD_SIZE_Y - VIEWPORT_SIZE_Y;
int offsetMinX = 0;
int offsetMinY = 0;
Image im;
//CLASSES//
Player p = new Player();
KeyInput ki = new KeyInput();
saveGame sg = new saveGame();
public Play(int state) {
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
im = new Image("res/images/play/Char_Up1.png");
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.translate(-camX, -camY);
g.drawImage(im, p.X, p.Y);
g.drawString("X: "+ p.X, 10+camX, 10+camY);
g.drawString("Y: "+ p.Y, 10+camX, 20+camY);
g.drawString("Cam_X: "+ camX, 10+camX, 30+camY);
g.drawString("Cam_Y: "+ camY, 10+camX, 40+camY);
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
sg.save();
Input i = gc.getInput();
if(i.isKeyDown(i.KEY_W)) {
p.Y -= 4;
System.out.println("UP!");
}
if(i.isKeyDown(i.KEY_S)) {
p.Y += 4;
System.out.println("DOWN!");
}
if(i.isKeyDown(i.KEY_A)) {
p.X -= 4;
System.out.println("LEFT!");
}
if(i.isKeyDown(i.KEY_D)) {
p.X += 4;
System.out.println("RIGHT!");
}
if(i.isKeyDown(i.KEY_ESCAPE)) {
sg.save();
System.exit(1);
}
camX = p.X - VIEWPORT_SIZE_X / 2;
camY = p.Y - VIEWPORT_SIZE_Y / 2;
if (camX > offsetMaxX){ camX = offsetMaxX; }
if (camX < offsetMinX){ camX = offsetMinX;}
if (camY > offsetMaxY){ camY = offsetMaxY; }
if (camY < offsetMinY){ camY = offsetMinY;}
}
public int getID() {
return 1;
}
}
答案 0 :(得分:1)
您正在保存类中创建一个新玩家,但您永远不会从外部保存将玩家分配给它。你需要将你的玩家从游戏板传递到你的保存方法。
将saveGame更改为:
public class saveGame {
BufferedWriter bw;
public void save(Player p) {
try {
bw = new BufferedWriter(new FileWriter("saves/saveTest.txt"));
//add save things
bw.write("X: " + p.X);
bw.newLine();
bw.write("Y: " + p.Y);
bw.close();
} catch (IOException e) {e.printStackTrace();}
}
}
然后将您的调用调用更改为:
sg.save(p);
答案 1 :(得分:0)
也许你早点写入缓冲区了?
如果你有很多线程,你应该尝试使用AtomicInteger来确保所有线程都获得相同的X和Y值(值得付出努力!)。
答案 2 :(得分:0)
您有两个单独的Player对象。您的游戏类中正在更新其x和y的一个,而不是在您的保存类中创建的另一个。简单的解决方法是使x和y静止。