我正在制作一款游戏(基于CityVille),你可以从上面俯视一个城市。我想这样做,以便我可以拖动世界来查看地图的不同部分。
这是我的代码:
package com.cgp.buildtown;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Game extends JPanel implements Runnable, MouseMotionListener {
private static final long serialVersionUID = 1L;
private BufferedImage banner;
private String chars = " `~1!2@3#4$5%6^7&8*9(0)-_=+qQwWeErRtTyYuUiIoOpP[{]}\\|aAsSdDfFgGhHjJkKlL;:'\"zZxXcCvVbBnNmM,<.>/?";
public String cityName;
private int[] offset;
public Thread thread;
private int totalOffset = 0;
private boolean[][] townAreas = new boolean[15][15];
public Game() {
super();
setBackground(new Color(69, 139, 0));
loadImages();
townAreas[8][8] = true;
townAreas[0][1] = true;
}
@Override
public void addNotify() {
super.addNotify();
thread = new Thread(this);
}
void findOffset() {
offset = new int[cityName.length()];
for (int i = 0; i < cityName.length(); i++) {
int ch = chars.indexOf(cityName.charAt(i));
if (ch < 0)
continue;
if (isShort(ch)) {
for (int j = i + 1; j < offset.length; j++) {
offset[j] += 25;
}
totalOffset += 25;
}
}
}
private boolean isShort(int ch) {
if (ch == 0 || ch == 1 || ch == 4 || ch == 14 || ch == 20 || ch == 22 || ch == 41 || ch == 42 || ch == 47 || ch == 48 || ch == 49 || ch == 50 || ch == 51 || ch == 52 || ch == 65 || ch == 69 || ch == 71 || ch == 72 || ch == 73 || ch == 74 || ch == 89 || ch == 91 || ch == 93)
return true;
else
return false;
}
private void loadImages() {
try {
banner = ImageIO.read(new File("res/banner.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(118, 238, 0));
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (townAreas[i][j]) {
g.fillRect(j * 400, i * 400, 400, 400);
}
}
}
int length = (cityName.length() * 45) - totalOffset;
int x = 400 - (length / 2);
for (int k = 0; k < cityName.length(); k++) {
int ch = chars.indexOf(cityName.charAt(k));
if (ch < 0)
continue;
g.drawImage(banner, (x + (k * 45)) - offset[k], 0, ((x + (k * 45)) + 45) - offset[k], 45, ch * 45, 0, (ch * 45) + 45, 45, null);
}
g.drawImage(banner, x - 15, 0, x, 45, 4276, 0, 4290, 45, null);
g.drawImage(banner, x + length, 0, x + length + 15, 45, 4291, 0, 4305, 45, null);
}
@Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
提前致谢!
答案 0 :(得分:0)
我认为你想要的效果的术语叫做“滑动地图”。这与您在Google地图中看到的用户体验相同。
有很多在Web浏览器中执行此类操作的示例,甚至还有一些JQuery插件。在Java2D中完成 - 你需要谷歌。
我们需要更多具体的信息,以帮助人们在黑暗中刺伤。