先生/女士对不起这个愚蠢的问题,因为我是一个新手,请帮助我检测在线程的帮助下移动的椭圆障碍物与在箭头键的帮助下移动矩形的玩家之间的碰撞(使用 Keylistener)。这是代码
public void init()
{
r = new Rectangle(0, 0, 50, 20);
addKeyListener(this);
Collision();
}
public void Collision()
{
if((r.x==x_pos) || (r.y==y_pos))
System.exit(0);
}
public void paint (Graphics g)
{
g.drawString("first click the left button of mouse keeping it over the rectangle then move the rectangle by arrow keys",20,10);
g.fillRect(r.x, r.y, r.width, r.height);
g.setColor (Color.red);
g.fillOval (x_pos , 10 , 2*radius, 2*radius);
g.setColor (Color.black);
g.fillOval (10 , y_pos , 4*radius, 1*radius);
g.setColor (Color.pink);
g.fillOval (x_pos , 40 , 2*radius, 2*radius);
g.setColor (Color.yellow);
g.fillOval (x_pos , 120 , 4*radius, 2*radius);
g.setColor (Color.gray);
g.fillOval (120 , y_pos , 2*radius, 1*radius);
g.setColor (Color.orange);
g.fillOval (x_pos , 150, 2*radius, 2*radius);
g.setColor (Color.magenta);
g.fillOval (x_pos, 260 , 3*radius, 2*radius);
g.setColor (Color.cyan);
g.fillOval (240 , y_pos , 2*radius, 2*radius);
g.setColor (Color.green);
g.fillOval (280 , y_pos , 2*radius, 2*radius);
g.setColor (Color.blue);
g.fillOval (x_pos , 290 , 2*radius, 2*radius);
g.setColor (Color.orange);
g.fillOval (x_pos , y_pos , 2*radius, 2*radius);
g.setColor (Color.magenta);
g.fillOval (x_pos , 360 , 2*radius, 2*radius);
g.setColor (Color.darkGray);
g.fillOval (x_pos , 390 , 2*radius, 2*radius);
}
public void start ()
{
Thread th1 = new Thread (this);
th1.start ();
}
public void stop()
{
}
public void destroy()
{
}
public void run ()
{
while(true)
{
x_pos++;
try
{
Thread.sleep(10);
}
catch(InterruptedException e){}
if(x_pos++> getSize().width)
x_pos=0;
repaint();
y_pos++;
try
{
Thread.sleep(10);
}
catch(InterruptedException e){}
if(y_pos++> getSize().height)
y_pos=0;
repaint();
}
}
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_LEFT)
{
r.x -= 10;
if(r.x < 0)
r.x = 0;
repaint();
}
else if(keyCode == KeyEvent.VK_RIGHT)
{
r.x += 10;
if(r.x > getSize().width-r.width)
{
r.x = getSize().width-r.width;
}
repaint();
}
else if(keyCode == KeyEvent.VK_UP)
{
r.y -= 10;
if(r.y < 0) r.y = 0;
repaint();
}
else if(keyCode == KeyEvent.VK_DOWN)
{
r.y += 10;
if(r.y > getSize().height-r.height)
{
r.y = getSize().height-r.height;
}
repaint();
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}