java中如何避免形状超出框架边界
我有一个程序,当按下箭头键时,它会超出画面。但是,我希望形状在超出该边界时反弹回来。有人能帮我吗java中如何避免形状超出框架边界,java,swing,animation,Java,Swing,Animation,我有一个程序,当按下箭头键时,它会超出画面。但是,我希望形状在超出该边界时反弹回来。有人能帮我吗 { JFrame frame = new JFrame("PacMan"); PacManObject panel = new PacManObject(); panel.setFocusable(true); panel.setRequestFocusEnabled(true); frame.setDefaultCloseOperation(JFrame
{
JFrame frame = new JFrame("PacMan");
PacManObject panel = new PacManObject();
panel.setFocusable(true);
panel.setRequestFocusEnabled(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
frame.setVisible(true);
frame.add(panel);
panel.addKeyListener(panel);
}
public static void main(String[] args) {
Runnable runnable = new Runnable(){
@Override
public void run() {
new PacMan();
}
};EventQueue.invokeLater(runnable);
}
class PacManObject extends JPanel implements KeyListener{
private int xLocation = 100;
private int yLocation = 100;
private int mouth = 280;
private int angle = 45;
private int xrandomLocation = 300;
private int yrandomLocation = 400;
private int xLocationEyes = 115;
private int yLocationEyes = 115;
我在那里画我的形状
@Override
public void paintComponent(Graphics graphics)
{
super.paintComponent(graphics);
//pacman
graphics.setColor(Color.yellow);
graphics.fillArc(xLocation, yLocation, 100, 100, angle, mouth);
//eyes
graphics.setColor(Color.BLACK);
graphics.fillOval(xLocationEyes, yLocationEyes, 20, 20);
food(graphics);
}
按箭头键时
@Override
public void keyPressed(KeyEvent keyboard) {
int keyboardPress = keyboard.getKeyCode();
if(keyboardPress == KeyEvent.VK_RIGHT){
xLocation += 30;
xLocationEyes += 30;
angle = 45;
repaint();
}
else if(keyboardPress == KeyEvent.VK_LEFT){
angle = -145;
xLocation -= 30;
xLocationEyes -= 30;
repaint();
}
}
加入一个范围检查,使用类似
if (xLocation + 100 >= getWidth()) {
xLocation = getWidth() - 100;
} else if (xLocation < 0) {
xLocation = 0;
}
如果(xLocation+100>=getWidth()){
xLocation=getWidth()-100;
}否则如果(xLocation<0){
xLocation=0;
}
对于y位置
一般来说,您应该有一个主/游戏循环,负责更新游戏的当前状态(基于输入的当前状态和其他要求(如重影的AI))并安排对UI的更新
这样,您将在密钥处理程序中设置一个标志,主/游戏循环将检查、更新玩家的状态和重新绘制的计划。这克服了第一次按键事件和重复事件之间延迟的固有问题
我也会考虑使用键绑定API在<代码>密钥监听器< /C> > < /P>
也许,看一看,想了解更多的想法,可以加入一个范围检查,它使用
if (xLocation + 100 >= getWidth()) {
xLocation = getWidth() - 100;
} else if (xLocation < 0) {
xLocation = 0;
}
如果(xLocation+100>=getWidth()){
xLocation=getWidth()-100;
}否则如果(xLocation<0){
xLocation=0;
}
对于y位置
一般来说,您应该有一个主/游戏循环,负责更新游戏的当前状态(基于输入的当前状态和其他要求(如重影的AI))并安排对UI的更新
这样,您将在密钥处理程序中设置一个标志,主/游戏循环将检查、更新玩家的状态和重新绘制的计划。这克服了第一次按键事件和重复事件之间延迟的固有问题
我也会考虑使用键绑定API在<代码>密钥监听器< /C> > < /P> 也许,请看一看,并获取更多的想法