我正在沿着“网格”移动形状。我似乎终于弄清楚了,但是我遇到了一个小问题;无论我尝试获得每个动作之间的特定时间间隔有多近,似乎仍然脱离了网格。我想使用我正在使用的当前方法,因为我了解这些人是如何以这种方式工作的。我知道它有时会出现随机移动“故障”,因为如果我将它向后移动第四次,无论如何它都应该锁定在网格上。这是我的代码(对不起,我只是在测试代码,没有评论和奇怪的放置):
主类:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
public class WhyOhWhy {
public int x;
public int y;
public static void main(String[] args) {
JFrame f = new JFrame();
InputHandler input = new InputHandler();
f.add(input);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,600);
input.doStuff();
}
}
输入处理类:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class InputHandler extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velX = 0, velY = 0;
int i = 0, j = 0;
TimeKeeper timeStart;
public void doStuff(){
velX = 0;
velY = 0;
}
public InputHandler() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.fill(new Ellipse2D.Double(x, y, 32, 32));
for(int i = 0;i <500;i+=32){
g2.drawRect(i, j, 32, 32);
for(int j=0;j<500;j+=32){
g2.drawRect(i, j, 32, 32);
}
}
}
public void actionPerformed(ActionEvent e) {
repaint();
x += velX;
y += velY;
if(TimeKeeper.isFinished() == true){
System.out.println("DONE");
TimeKeeper.resetTimer(false);
velX = 0;
velY = 0;
setEnabled(true);
}
}
public void up() {
//System.out.println("Moving up");
timeStart = new TimeKeeper(185);
velY = -1;
velX = 0;
setEnabled(false);
}
public void down() {
//System.out.println("Moving down");
setEnabled(false);
timeStart = new TimeKeeper(185);
velY = 1;
velX = 0;
}
public void left() {
//System.out.println("Moving left");
setEnabled(false);
timeStart = new TimeKeeper(185);
velY = 0;
velX = -1;
}
public void right() {
//System.out.println("Moving right");
setEnabled(false);
timeStart = new TimeKeeper(185);
velY = 0;
velX = 1;
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_W) {
up();
}
if (code == KeyEvent.VK_S) {
down();
}
if (code == KeyEvent.VK_A) {
left();
}
if (code == KeyEvent.VK_D) {
right();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
velX = 0;
velY = 0;
}
}
计时员类:
import java.util.Timer;
import java.util.TimerTask;
public class TimeKeeper {
Timer timer;
public static boolean isDone = false;
public TimeKeeper(int seconds) {
timer = new Timer();
isDone = false;
timer.schedule(new RemindTask(), seconds );
}
class RemindTask extends TimerTask {
public void run() {
//System.out.println("Time's up!");
isDone = true;
timer.cancel(); //Terminate the timer thread
}
}
public static boolean isFinished() {
return isDone;
}
public static void resetTimer(boolean done) {
isDone = done;
}
}
谢谢!