[我正在做一个学校项目,我发现用Java编写代码非常困难,我一直在尝试制作类似于Super Mario的2D平台游戏,我首先制作了主菜单,您使用其他JFrame(例如New Game,Controls等),但是一旦必须创建第一个关卡,我便开始发现障碍。我不知道该如何显示移动的角色,加载的背景,计时器,硬币,实际上是所有内容。我找不到适合初学者的任何教程,因为他们并没有真正详细解释如何使用Java swing创建2d平台游戏。
public class MainMenu2 {
MainMenu2() throws IOException{
JFrame Main_Menu = new JFrame("Main Menu");
Main_Menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int widthScreen = screenSize.width;
int heightScreen = screenSize.height;
BufferedImage backgroundImage = ImageIO.read(new File("P:\\My Pictures\\background1.jpg"));
JLabel background = new JLabel(new ImageIcon(backgroundImage));
Image scaleBackground = backgroundImage.getScaledInstance(widthScreen, heightScreen, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(scaleBackground);
Main_Menu.setContentPane(new JLabel(imageIcon));
BufferedImage logoImage = ImageIO.read(new File("P:\\Computer Science\\Coursework\\CourseWorkGame\\logo.png"));
JLabel logo = new JLabel(new ImageIcon(logoImage));
logo.setBounds(((widthScreen/3)-75),((200/2)+145),700,150);
Main_Menu.getContentPane().add(logo);
Main_Menu.setSize(new Dimension(widthScreen, heightScreen));
Main_Menu.setUndecorated(true); //makes the bar at the top disappear
Main_Menu.setLayout(null);
Main_Menu.setLocationRelativeTo(null);
Main_Menu.setVisible(true);
Main_Menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton new_game = new JButton("New Game");
new_game.setBounds(((widthScreen/2)-75),((heightScreen/2)+90),150,50);
new_game.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
NewGame buttonone = new NewGame(widthScreen,heightScreen);
} catch (IOException ex) {
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
}
Main_Menu.setVisible(false);
}
});
Main_Menu.add(new_game);
Loader-加载主菜单
public class MainMenu {
public static void main(String[] args) throws IOException {
MainMenu2 abc = new MainMenu2();
}
主要思想是绘制并更改坐标,然后重画并删除第一个图形,它将产生位移效果,请检查此https://www.youtube.com/watch?v=vbI2NvIcrSY&t=229s