2012-11-29 22 views
0

我已經在800x600px板上成功地創建了一個由50x50方格組成的16x12網格的代碼。如您所見,玩家移動到玩家鼠標點擊的座標。檢測物體上的鼠標點擊Slick2d

網格的每個方格都有一個毛氈對象(場),它可以是乳房(鎖定)。如果字段鎖定屬性設置爲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

首先,你應該初始化板在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; 
} 

下一頁修改更新的部分( )方法更新平面座標,因此模糊不清:

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;  
     } 
} 
0

很簡單!

int mx = Mouse.getX(); 
int my = Mouse.getY(); 

但是,它給你的世界cordinates,你必須把它轉化爲像素:

int mx = Mouse.getX(); 
int my = Mouse.getY() * -1 + (Window.WIDTH/2) + 71;