gpt4 book ai didi

java - 玩家 Sprite 在 Java 2D 游戏中不会移动(重绘)

转载 作者:行者123 更新时间:2023-11-30 06:47:31 27 4
gpt4 key购买 nike

我是 Java 新手,我正在尝试制作一个简单的游戏来娱乐。我首先尝试将 repaint 放入 PaintComponent() 中,它一直有效,直到我尝试添加一些背景。有谁知道如何让我的玩家在有或没有“重绘”的情况下移动?

屏幕类别

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Frame extends JFrame implements KeyListener
{
Map map;

public static void main(String[] args)
{
Frame frame = new Frame();
frame.addKeyListener(new Frame());
frame.setVisible(true);
}

public Frame()
{
setInit();
}

private void setInit()
{
map = new Map();
add(map);

setSize(800, 800);//frame size 300 width and 300 height
setTitle("Eerste Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

setResizable(false);
setLayout(new GridLayout(1,1,0,0));
setFocusable(true);
setVisible(true);
}

public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();

map.movePlayer(keyCode);
}

public void keyReleased(KeyEvent e)
{

}

public void keyTyped(KeyEvent e)
{

}
}

map 类

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

class Map extends JPanel
{
Player player;
BufferedImage map;

public Map() {
player = new Player();
try{map = ImageIO.read(new File("img/map.png"));}catch (Exception e){};
}

public void movePlayer(int keyPressed)
{
player.move(keyPressed);
revalidate();
repaint();
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(player.img,player.getX(),player.getY(), null);
}

}

玩家等级

import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

class Player
{
BufferedImage img = null;
private int x = 100;
private int y = 100;

public Player()
{
try{img = ImageIO.read(new File("img/bob.png"));}catch (Exception e){}
}

public int getX()
{
return x;
}

public int getY()
{
return y;
}

public void move(int keyPressed)
{
if(keyPressed == KeyEvent.VK_W) {
// handle up
y = y - 5;
}
if (keyPressed == KeyEvent.VK_A) {
// handle links
x = x - 5;
}
if (keyPressed == KeyEvent.VK_S) {
// handle onder
y = y + 5;
}
if (keyPressed == KeyEvent.VK_D ) {
// handle right
x = x + 5;
}

}
}

最佳答案

您不必要创建一个新的 Frame 对象作为 KeyListener,因此 KeyListener 事件全部转到不同的 Frame 实例,而不是显示的实例。改变

frame.addKeyListener(new Frame());

至:

frame.addKeyListener(frame);

现在 KeyListener 驱动真正显示的感兴趣的 Frame 实例。

<小时/>

其他问题,这个不好:

catch (Exception e){}

始终捕获特定异常,并且几乎总是,您应该处理它们。至少做这样的事情:

catch (IOException e) {
e.printStacktrace();
}

关于java - 玩家 Sprite 在 Java 2D 游戏中不会移动(重绘),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43437635/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com