我正在制作一个游戏,屏幕上有两个球。一个是计算机控制的,单独移动,另一个用左右键控制。
public class StartingPoint extends Applet implements Runnable, KeyListener
{
int x = 356;
int y = 74;
double dx = 5;
double dy = 6;
int radius = 20;
//private Image i;
//private Graphics doubleG;
int x2 = 0;
int y2 = 0;
double dx2 = 0;
double dy2 = 0;
int radius2 = 20;
boolean left = false;
boolean right = false;
@Override
public void init()
{
setSize(800, 600);
setVisible(true);
setFocusable(true);
System.out.println("Game Started!");
System.out.println("init");
}
@Override
public void start()
{
Thread thread = new Thread(this);
thread.start();
System.out.println("start");
}
@Override
public void run()
{
System.out.println("run");
while (true)
{
x += dx;
y += dy;
repaint(); //Goes to update method
if (x + dx > this.getWidth() -radius -1)
{
x = this.getWidth() - radius - 1;
dx = - dx;
}
else if (x + dx < 0 + radius)
{
x = 0 + radius;
dx = -dx;
}
else
{
x += dx;
}
if (y + dy > this.getHeight() -radius -1)
{
y = this.getHeight() - radius - 1;
dy = - dy;
}
else if (y + dy < 0 + radius)
{
y = 0 + radius;
dy = -dy;
}
else
{
y += dy;
}
System.out.println("New stuffs");
x2 += dx2;
y2 += dy2;
repaint(); //Goes to update method
if (x2 + dx2 > this.getWidth() -radius2 -1)
{
x2 = this.getWidth() - radius2 - 1;
dx2 = - dx2;
}
else if (x2 + dx2 < 0 + radius2)
{
x2 = 0 + radius2;
dx2 = -dx2;
}
else
{
x2 += dx2;
}
if (y2 + dy2 > this.getHeight() -radius2 -1)
{
y2 = this.getHeight() - radius2 - 1;
dy2 = - dy2;
}
else if (y2 + dy2 < 0 + radius2)
{
y2 = 0 + radius2;
dy2 = -dy2;
}
else
{
y += dy;
}
try
{
Thread.sleep(17);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e)
{
System.out.println("KeyPressed");
switch(e.getKeyCode())
{
case KeyEvent.VK_LEFT:
moveLeftPressedCode();
System.out.println("VK LEFT");
break;
case KeyEvent.VK_RIGHT:
moveRightPressedCode();
System.out.println("VK RIGHT");
break;
}
}
public void keyReleased(KeyEvent e2)
{
System.out.println("KeyReleased");
switch(e2.getKeyCode())
{
case KeyEvent.VK_LEFT:
moveLeftReleasedCode();
break;
case KeyEvent.VK_RIGHT:
moveRightReleasedCode();
break;
}
}
public void moveLeftPressedCode()
{
left = true;
System.out.println("");
}
public void moveLeftReleasedCode()
{
left = false;
}
public void moveRightPressedCode()
{
right = true;
}
public void moveRightReleasedCode()
{
right = false;
}
public void keyEventLeft()
{
if(dx2 >= -7)
{
while (left = true)
{
dx2 = - 7;
}
}
}
public void keyEventRight()
{
if(dx2 <= 7)
{
while (right = true)
{
//nothing yet
}
}
}
@Override
public void stop()
{
}
@Override
public void destroy()
{
}
@Override
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
g.setColor(Color.GREEN);
g.fillOval(x2 - radius2, y2 - radius2, radius2 * 2, radius2 * 2);
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
我遇到的问题是,当我按下左键(或右键)时,该方法不会被调用,因此没有检测到按键。如何修复此问题或我需要添加什么才能让游戏检测到我的按键? - 谢谢你。