我正在尝试制作几何战争风格的游戏,但遇到了障碍。我一直在试图找出一种方法来平稳地移动我的图形对象。但它只向一个方向移动。例如,如果我按下向上按钮,它就会上升,然后当我按下它上面的右键时,我会斜向右上角移动。但我希望我的对象从笔直向上平稳地转向右上角。到目前为止,这是我的代码:
public class MoveTest extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
double x = 0, y = 0, velX = 0, velY = 0;
private Set<Integer> pressed = new HashSet<Integer>();
private static int WIDTH = 800;
private static int HEIGHT = 600;
private double d = 0;
private double topSpeed = 0;
private boolean stop = false;
private double a = 0;
PVector location;
PVector velocity;
PVector acceleration;
public MoveTest() {
location = new PVector(WIDTH/2,HEIGHT/2);
velocity = new PVector(0,0);
acceleration = new PVector(0,0);
topSpeed = 5.0;
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.GREEN);
g2.drawOval((int)location.x, (int)location.y, 40, 40);
}
void update() {
velocity.add(acceleration);
if(stop == false) {
velocity.limit(topSpeed);
}
else {
velocity.decellerate(0);
}
location.add(velocity);
}
public void north() {
acceleration = new PVector(0,-5);
}
public void south() {
acceleration = new PVector(0,5);
}
public void west() {
acceleration = new PVector(-5,0);
}
public void east() {
acceleration = new PVector(5,0);
}
public void northEast() {
acceleration = new PVector(5,-5);
}
public void northWest() {
acceleration = new PVector(-5,-5);
}
public void southEast() {
acceleration= new PVector(5,5);
}
public void southWest() {
acceleration = new PVector(-5,5);
}
public void stop(){
stop = true;
}
public void actionPerformed(ActionEvent arg0) {
//System.out.println("" + velocity.x + " " + velocity.y);
repaint();
update();
checkEdges();
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
stop = false;
pressed.add(code);
if(pressed.size() > 1) {
if(pressed.contains(KeyEvent.VK_W) && pressed.contains(KeyEvent.VK_D)) {
northEast();
}
if(pressed.contains(KeyEvent.VK_W) && pressed.contains(KeyEvent.VK_A)) {
northWest();
}
if(pressed.contains(KeyEvent.VK_S) && pressed.contains(KeyEvent.VK_D)) {
southEast();
}
if(pressed.contains(KeyEvent.VK_S) && pressed.contains(KeyEvent.VK_A)) {
southWest();
}
}
else if(pressed.size() == 1){
if(code == KeyEvent.VK_W) {
north();
}
if(code == KeyEvent.VK_S) {
south();
}
if(code == KeyEvent.VK_D) {
east();
}
if(code == KeyEvent.VK_A) {
west();
}
}
}
public void keyReleased(KeyEvent e) {
pressed.remove(e.getKeyCode());
if(pressed.size() == 0) {
stop();
}
}
public void keyTyped(KeyEvent e) {
}
void checkEdges() {
if(location.x > WIDTH) {
location.x = 0;
}
else if(location.x < 0) {
location.x = WIDTH;
}
if(location.y > HEIGHT) {
location.y = 0;
}
else if(location.y < 0) {
location.y = HEIGHT;
}
}
}
任何帮助,将不胜感激。