好的,所以我想要的是始终移动的矩形,但是当您按下左右箭头时,会通过增加或减少角度来改变方向。使用此代码,squaure 会按正确的方向移动,但是当我按下键时,方向不会改变。
import java.awt.*;
import java.awt.Color;
import javax.swing.Timer;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
public class Fields extends JPanel implements ActionListener, KeyListener{
Timer tm = new Timer(5, this);
double x = 250, y = 250, vel = 0.2, angle = 90;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.GREEN);
g.fillRect((int)x, (int)y, 5, 5);
tm.start();
}
public void keyTyped(KeyEvent e)
{
if (e.getKeyCode() == 37) {angle--;}
if (e.getKeyCode() == 39) {angle++;}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == 37) {angle--;}
if (e.getKeyCode() == 39) {angle++;}
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == 37) {angle--;}
if (e.getKeyCode() == 39) {angle++;}
}
public void actionPerformed(ActionEvent e)
{
x += (velX * (float)Math.cos(Math.toRadians(angle - 90)));
y += (velX * (float)Math.sin(Math.toRadians(angle - 90)));
repaint();
}
public Fields()
{
this.addKeyListener(this);
}
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 500);
Fields fi = new Fields();
f.add(fi);
f.setVisible(true);
}
}