我正在创建一个Java游戏,其中有一个球(球员)和其他球应该到达这个球员(敌人等)。玩家可以使用箭头键移动来逃脱这些敌人。我计算了数学,以便在玩家移动后找到敌人的新X和Y位置,但我无法找到一种方法来平滑地动画这些动作。我尝试使用线程,但它没有正常工作,所以我删除了一些代码。还有一种方法可以在游戏开始时在新位置和/或不同时间创建新敌人,但我无法让计时器工作。这是迄今为止该程序的代码。
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.awt.event.*;
import javax.swing.*;
public class game implements Runnable {
JFrame frame;
int myX = 400;
int myY = 400;
//x and y of second oval
int X2 = 200;
int Y2 = 200;
Canvas canvas;
BufferStrategy bufferStrategy;
boolean running = true;
public game() {
frame = new JFrame("Basic Game");
JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(500, 500));
panel.setLayout(null);
canvas = new Canvas();
canvas.setBounds(0, 0, 500, 500);
canvas.setIgnoreRepaint(true);
panel.add(canvas);
canvas.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
moveIt(evt);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
canvas.createBufferStrategy(2);
bufferStrategy = canvas.getBufferStrategy();
canvas.requestFocus();
}
public void run() {
while (running = true) {
Paint();
try {
Thread.sleep(25);
} catch (InterruptedException e) {
}
}
}
public static void main(String[] args) {
game ex = new game();
new Thread(ex).start();
}
public void Paint() {
Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
g.clearRect(0, 0, 500, 500);
Paint(g);
bufferStrategy.show();
}
protected void Paint(Graphics2D g) {
//paints the two ovals
g.fillOval(myX, myY, 30, 30);
g.fillOval(X2,Y2, 30, 30);
}
public void moveIt(KeyEvent evt) {
switch (evt.getKeyCode()) {
//calculates positions for second oval
case KeyEvent.VK_DOWN:
myY += 10;
X2 = (int) ((X2 + myX) * 0.5);
Y2 = (int) ((Y2 + myY) * 0.5);
break;
case KeyEvent.VK_UP:
myY -= 10;
X2 = (int) ((X2 + myX) * 0.5);
Y2 = (int) ((Y2 + myY) * 0.5);
break;
case KeyEvent.VK_LEFT:
myX -= 10;
X2 = (int) ((X2 + myX) * 0.5);
Y2 = (int) ((Y2 + myY) * 0.5);
break;
case KeyEvent.VK_RIGHT:
myX += 10;
X2 = (int) ((X2 + myX) * 0.5);
Y2 = (int) ((Y2 + myY) * 0.5);
break;
}
}
}
我将非常感谢能够通过球和动画的动画获得任何帮助。