我在Java课上练习时遇到了一些问题,我在游戏中制作了两个矩形,我需要将这些数字从一侧移到另一侧。我已经拥有了运动类,并制作了机芯线程的实例,但它似乎并没有移动。
这是我的代码: 实体类
class Entity implements Drawable{
Point pos;
Rectangle body;
boolean rigid;
public Entity(){
pos = new Point(0,0);
body = new Rectangle(pos, new Dimension(0,0));
}
public Entity(Point p, Dimension d){
pos = new Point(p);
body = new Rectangle(pos, d);
}
public Entity(int x, int y, int width, int height){
pos = new Point(x,y);
body = new Rectangle(pos, new Dimension(width, height));
}
public BufferedImage getActualImage(){
Dimension d = body.getSize();
return new BufferedImage(d.width, d.height, BufferedImage.TYPE_3BYTE_BGR);
}
}
这个类是游戏环境,我在窗口添加对象。
class Field extends JPanel{
Player p1;
int i=0;
static ArrayList<Entity> objects = new ArrayList<Entity>();
private ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
revalidate();
repaint();
}
};
public Field(){
//Implementar patron de disen/o
p1 = setupPlayer();
Game.objects.add(p1);
//Player p2 = new Player();
//p2.setImageRightRun("hero\\run.png");
//Game.objects.add(p2);
Entity e1 = new Entity(0, 520, 600, 50);
Blocks block1 = new Blocks(260, 370, 100, 20);
Blocks block2 = new Blocks(190, 440, 100, 20);
Goal block3 = new Goal(300, 270, 50,50);
Game.objects.add(e1);
Game.objects.add(block1);
Game.objects.add(block2);
Game.objects.add(block3);
new Thread(new MovementBlock(block1)).start(); //movement thread//
PlayerBehaviour pb = new PlayerBehaviour(p1);
this.addKeyListener(pb);
Timer tick = new Timer(20, actionListener);
tick.setInitialDelay(0);
tick.start();
}
块类
class Blocks extends Entity{
public Blocks(int x, int y, int ancho, int largo){
super(x,y,ancho,largo);
}
}
和运动的线程
class MovementBlock implements Runnable{
Blocks block;
int velX = 2;
public MovementBlock(Blocks block){
this.block = block;
}
public void run(){
if(block.pos.x < 0 || block.pos.x > 500){
velX = -velX;
}
block.pos.x = block.pos.x + 1;
repaint();
}
}
这是我对街区和运动的代码,是不是我没有考虑这个运动?
感谢阅读。
答案 0 :(得分:0)
如果移动是连续动作,则run
方法需要是循环。你写它的方式,它只运行一次。将其添加到MovementBlock
。
boolean running = true;
int frameDelay = 20; // ms
public void stop() { running = false; }
public void run() {
while (running) {
try {
if (block.pos.x < 0 || block.pos.x > 500) {
velX = -velX;
}
block.pos.x += velX;
repaint();
Thread.sleep(frameDelay);
} catch (InterruptedException e) {}
}
}