我目前有一个瓦片地图,并且我只在屏幕上显示地图的特定部分,而用户在中间,但是我无法做到这一点,因此角色在瓦片之间可以自由移动,而不是瓦片之间
public void paintComponent(Graphics g) {
super.paintComponent(g); //required to ensure the panel si correctly redrawn
for(int i = 0; i <visibleHeight;i=i+1){
for(int j = 0; j <visibleHeight;j=j+1){
g.setColor(backgroundColor);
g.fillRect(j*boxWidth, i*boxHeight, boxWidth, boxHeight);
g.setColor(Color.black);
g.drawRect(j*boxWidth, i*boxHeight, boxWidth, boxHeight);
g.fillRect(j*boxWidth, i*boxHeight, boxWidth, boxHeight);
if ((hero.getY()-visibleHeight/2+i) < world.length && (hero.getX()-visibleHeight/2+j) >= 0 // check if the desired
&& (hero.getY()-visibleHeight/2+i) >= 0 && (hero.getX()-visibleHeight/2+j) < world.length){// location to draw is within bounds
// draw the map according to the player location
if (world[hero.getY()-visibleHeight/2+i][hero.getX()-visibleHeight/2+j] == 1){ // subtract visibleHeight/2+i
g.drawImage(tree,j*boxWidth, i*boxHeight, boxWidth, boxHeight, this); //to get all boxes from half
}else if(world[hero.getY()-visibleHeight/2+i][hero.getX()-visibleHeight/2+j] == 2){ // the visible height under
g.setColor(trailColor); // and half the visible height above the player
g.fillRect(j*boxWidth, i*boxHeight, boxWidth, boxHeight);
}else{
g.setColor(backgroundColor);
g.fillRect(j*boxWidth, i*boxHeight, boxWidth, boxHeight);
}
}
}
}
clock.update();
frameRate.update();
hero.update(clock, world); // update hero
hero.draw(g); // update hero
//update the content
frameRate.draw(g,10,10);
//draw the framerate
//request a repaint
repaint();
}
public void draw(Graphics g) {
g.setColor(Color.BLUE); //There are many graphics commands that Java can use
g.fillRect(512, 512, this.width, this.length);
g.setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.setColor(Color.black);
g.drawString(this.x + ":" + this.y, 200, 400);
}
public void update(Clock clock, int[][] world){
//boxWidth*world.length is equal to the total size of the map converted to pixels
if (this.x + xShift*clock.getElapsedTime()*((GamePanel.boxWidth*world.length)/1024) > 0
&& (this.x + xShift*clock.getElapsedTime()*(GamePanel.boxWidth*world.length)/1024) < GamePanel.boxWidth*world.length){
// multiply by (GamePanel.boxWidth*world.length)/1024) to make it so you move the same number of blocks regardless of the visible height
this.x += xShift*clock.getElapsedTime()*((GamePanel.boxWidth*world.length)/1024);
}if (this.y + yShift*clock.getElapsedTime()*((GamePanel.boxWidth*world.length)/1024) > 0
&& (this.y + yShift*clock.getElapsedTime()*(GamePanel.boxWidth*world.length)/1024) < GamePanel.boxWidth*world.length){
// multiply by (GamePanel.boxWidth*world.length)/1024) to make it so you move the same number of blocks regardless of the visible height
this.y += yShift*clock.getElapsedTime()*((GamePanel.boxWidth*world.length)/1024);
}
}