我已经制作了这个代码,可以在800x600px主板上成功创建一个50x50正方形的16x12网格。 如您所见,玩家移动到玩家的坐标鼠标点击。
网格的每个方格上都有一个毛毡(场)对象,可以是拉(锁定)。如果字段锁定属性设置为1,则不应将播放器移动到该位置。
我如何检测玩家试图继续实现此目标的字段?
public class SimpleGame extends BasicGame{
private Image plane;
private float planeX;
private float planeY;
public SimpleGame()
{
super("SpilTest");
}
@Override
public void init(GameContainer gc) throws SlickException {
plane = new Image("figur.png");
}
@Override
public void update(GameContainer gc, int delta) throws SlickException {
Input input = gc.getInput();
if (input.isMousePressed(input.MOUSE_LEFT_BUTTON)) {
this.planeX = input.getMouseX() - 30;
this.planeY = input.getMouseY() - 50;
}
}
public void render(GameContainer gc, Graphics g) throws SlickException {
Felt board[][] = nytGrid();
int distancex = 0;
int distancey = 0;
int counter = 0;
for (int i=0; i < board.length ; i++) {
for (int j=0; j < board[i].length ; j++) {
if (board[i][j].getLaast() == 1) {
g.setColor(Color.red);
g.fillRect(distancex, distancey, 50, 50);
}
distancex += 50;
counter++;
if (counter == 16) {
distancey += 50;
distancex = 0;
counter = 0;
}
}
}
g.drawImage(plane, planeX, planeY);
}
public static void main(String[] args) throws SlickException {
AppGameContainer app = new AppGameContainer(new SimpleGame());
app.setDisplayMode(800, 600, false);
app.setTargetFrameRate(60);
app.start();
}
public Felt[][] nytGrid() {
Felt [][] board = new Felt[16][12];
for (int i=0; i < board.length ; i++) {
for (int j=0; j < board[i].length ; j++) {
int x = i;
int y = j;
board[i][j] = new Felt(x, y);
if (i == 5 && j == 5) {
board[i][j].setLaast(1);
}
}
}
return board;
}
}
答案 0 :(得分:0)
首先,您可能应该在init()方法中初始化板而不是渲染,因此它不必每帧都执行它,并在平面,planeX和planeY声明旁边移动网格的声明在课堂上。
现在要禁用移动到锁定的方块,首先添加一个方法来检查某个坐标处的方块是否被锁定,所以有以下几点:
private boolean isLocked(int x, int y) {
int square = board[x/50][y/50];
if (square == 1) return true;
else return false;
}
接下来修改update()方法中更新平面坐标的部分,隐约可以这样:
if (input.isMousePressed(input.MOUSE_LEFT_BUTTON)) {
int destX = input.getMouseX() - 30;
int destY = input.getMouseY() - 50;
if (!isLocked(destX, destY)) {
this.planeX = destX;
this.planeY = destY;
}
}
答案 1 :(得分:0)
很简单!
int mx = Mouse.getX();
int my = Mouse.getY();
但是,它会为您提供世界坐标,您必须将其转换为像素:
int mx = Mouse.getX();
int my = Mouse.getY() * -1 + (Window.WIDTH / 2) + 71;