我编写了一个简单的 2D Java 游戏,其中有一个玩家在 2D 地图上的俯视图,它随着键盘箭头输入(上、下、左、右)移动,我的 Play 类包含我的所有游戏代码有几种方法,主要的方法是渲染,它将所有内容绘制到屏幕上,例如实际的播放器和地图,以及处理键盘输入、移动播放器和更新图像的更新。
这是我的游戏课程的代码:
imports are here
public class Play extends BasicGameState{
Animation bucky, movingUp, movingDown, movingLeft, movingRight;
Image worldMap;
int[] duration = {200, 200};//how long frame stays up for
float buckyPositionX = 0;
float buckyPositionY = 0;
float shiftX = buckyPositionX + 320;//keeps user in the middle of the screem
float shiftY = buckyPositionY + 160;//the numbers are half of the screen size
java.awt.geom.Rectangle2D.Float rectOne = new Rectangle2D.Float(shiftX, shiftY,90,90);
java.awt.geom.Rectangle2D.Float rectTwo = new Rectangle2D.Float(500 + buckyPositionX, 330 + buckyPositionY, 210, 150);
public Play(int state){
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
worldMap = new Image("res/world.png");
Image[] walkUp = {new Image("res/b.png"), new Image("res/b.png")}; //these are the images to be used in the "walkUp" animation
Image[] walkDown = {new Image("res/f.png"), new Image("res/f.png")};
Image[] walkLeft = {new Image("res/l.png"), new Image("res/l.png")};
Image[] walkRight = {new Image("res/r.png"), new Image("res/r.png")};
movingUp = new Animation(walkUp, duration, false);
movingDown = new Animation(walkDown, duration, false);
movingLeft = new Animation(walkLeft, duration, false);
movingRight = new Animation(walkRight, duration, false);
bucky = movingDown;//facing screen initially on startup
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
worldMap.draw(buckyPositionX, buckyPositionY);//position 0,0
bucky.draw(shiftX, shiftY);//makes him appear at center of map
g.fillRect((float)rectOne.getX(), (float)rectOne.getY(), (float)rectOne.getWidth(), (float)rectOne.getHeight());
g.fillRect((float)rectTwo.getX(), (float)rectTwo.getY(), (float)rectTwo.getWidth(), (float)rectTwo.getHeight());
}
public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException{
Input input = gc.getInput();
//up
if(input.isKeyDown(Input.KEY_UP)){
bucky = movingUp;//changes the image to his back
buckyPositionY += 2;;//increase the Y coordinates of bucky (move him up)
if(buckyPositionY>162){//if I reach the top
buckyPositionY -= 2;//stops any further movement in that direction
}
}
//down
if(input.isKeyDown(Input.KEY_DOWN)){
bucky = movingDown;
buckyPositionY -= 2;
if(buckyPositionY<-550){
buckyPositionY += 2;//basically change the direction if + make -
}}
//left
if(input.isKeyDown(Input.KEY_LEFT)){
bucky = movingLeft;
buckyPositionX += 2;
if(buckyPositionX>324){
buckyPositionX -= 2;//delta * .1f
}}
//right
if(input.isKeyDown(Input.KEY_RIGHT)){
bucky = movingRight;
buckyPositionX -= 2;
if(buckyPositionX<-776){
buckyPositionX += 2;
}}}
public int getID(){
return 1;
}}
我需要通过将 rectTwo 放在我的更新类中来更新它的位置,但是在编写代码来执行此操作时遇到问题,有人可以帮我解决这个问题吗?