我想要的是当我按下弧形(在这种情况下是pacman)并与椭圆形状(它的食物)相撞时,椭圆形将随机显示到框架中的另一个位置。
答案 0 :(得分:2)
基本思想是确定玩家是否与食物相交,如......
public boolean intersects() {
int tx = xLocation;
int ty = yLocation;
int rx = xrandomLocation;
int ry = yrandomLocation;
int rw = 20 + rx;
int rh = 20 + ry;
int tw = 100 + tx;
int th = 100 + ty;
// overflow || intersect
return ((rw < rx || rw > tx)
&& (rh < ry || rh > ty)
&& (tw < tx || tw > rx)
&& (th < ty || th > ry));
}
当方法返回true时,您想要计算食物的新位置
也许像......
private Random random = new Random();
//...
xrandomLocation = random.nextInt(getWidth()) - 20;
yrandomLocation = random.nextInt(getHeight()) - 20;
Java的2D图形API具有非常强大的shapes API,可让您更简单地检查碰撞
您还应停止使用KeyListener
API并开始使用Key Bindings API,这有助于解决KeyListener
遭受的焦点相关问题。
此外,我在last question中提出的所有建议仍然有效
答案 1 :(得分:-2)
您的结构有点偏差,PacmanObject不需要扩展JPannel或实现KeyListener。无论你的JPannel是什么,它都需要使用方法addKeyListener,KeyListener通常是匿名的。是的,你需要检查每次pacman移动后食物和pacman是否处于相同的位置。您还需要生成一个随机位置,但这些都不是很难。我已经编写了一个框架供您编写代码,当然嵌套类应该可以移动到自己的文件中。
包pacman;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Pacman extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Pacman frame = new Pacman();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Pacman() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new View();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
public class View extends JPanel {
PacmanObject p;
FoodObject f;
/**
* Create the panel.
*/
public View() {
super();
addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
onKeyEvent(e);
}
@Override
public void keyReleased(KeyEvent e) {
}
});
}
public void onKeyEvent(KeyEvent keyPress) {
p.move(keyPress);
if (/* check if f and p colide*/true) {
f.reposition();
}
p.repaint(this.getGraphics());
f.repaint(this.getGraphics());
}
}
public class FoodObject {
// Fields
FoodObject() {
// init fields
}
public void repaint(Graphics graphics) {
// repaint
}
public void reposition() {
// generate random position
}
}
public class PacmanObject {
// Fields
PacmanObject() {
// init fields
}
public void repaint(Graphics graphics) {
// repaint
}
public void move(KeyEvent keyPress) {
/// Move pacman
}
}
}
希望有所帮助