Java - 对象数组不会移动

时间:2016-12-16 14:15:04

标签: java object multidimensional-array 2d-games

好的,所以我正在制作一场下雨的游戏。我用一个阵列创建了狗,然后用一个新的线程将它们添加到我的主要课程中,除了狗之外的所有狗都没有动,我无法弄清楚原因。任何人都可以帮我发现我的错误吗? (注意:这不是作业,我在空闲时间这样做)

这是我的一些代码: 主要课程:

// instance variables
private double width, height;
Dogs[] doggo = new Dogs[4]; // an array of dogs
int count = 3; // counts the amount of lives remaining
int counter = 0; // counts how many dogs are saved

public void drawGraphics(){
    // draw the dogs
    for (int i = 0; i < 5; i++) {
        double x = rand.nextDouble(SIZE, (getWidth()-10)-SIZE);

        doggo[i] = new Dogs(SIZE, speed, this);
        // add dog to top of the window
        add(doggo[i], x, 0);
        new Thread(doggo[i]).start(); // animate the dogs
        //System.out.println("try");
    }

    for (int i = 0; i < 5; i++) {
        double x = rand.nextDouble(10, (getWidth()-10)-SIZE);

        doggo[i] = new Dogs(SIZE, speed*2, this);
        // add dog to top of the window
        add(doggo[i], x, 0);
        new Thread(doggo[i]).start(); // animate the dogs
        //System.out.println("try");
    }

}

狗类:

// constants
private static final double DELAY = 50;

// instance variables
private double size, speed;
DoggoRescue game; // to recognize use of dogs in DoggoRescue game
GImage dog;    

public Dogs(double size, double speed, DoggoRescue game){
    // save the parameters to the instance variables
    this.game = game;
    this.size = size;
    this.speed = speed;

    // draw an image of the dog
    dog = new GImage("Doggo.png");
    dog.setSize(size, size);
    add(dog, -size/2, -size/2);
}

// animate the dog
public void run(){
    oneTimeStep();
    pause(DELAY);
}

// called by run(), move the dog
private void oneTimeStep(){
    // move dog
    move(0, speed);
    //System.out.println("try");
    pause(DELAY);
    // call checkCollision of the main class
    game.checkCollision(this);
}

1 个答案:

答案 0 :(得分:0)

修改

您的Dogs类需要实现Runnable,以便在启动线程时调用run()方法。

您可以在此处查看oracle文档以获取示例: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html