【问题标题】:Java - Array of objects won't moveJava - 对象数组不会移动
【发布时间】:2016-12-16 14:15:03
【问题描述】:

好的,所以我正在制作一个会下雨的游戏。我用一个数组创建了狗,并用一个新线程将它们添加到我的主类中,但除了狗之外,所有的狗都没有移动,我不知道为什么。谁能帮我发现我的错误? (注意:这不是作业,我是在空闲时间做的)

这是我的一些代码: 主类:

// 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);
}

【问题讨论】:

  • 只是快速浏览了一下,没有真正的分析...但是-size/2 似乎可能是个问题。你的意思是--size/2 还是(-1*size)/2?哈哈@doggo
  • 我认为问题在于您在非 UI 线程上运行 UI 代码,不是吗?
  • 这不是您要解决的问题,但我不明白当doggo 只有 4 个元素时,您如何没有从访问doggo[4] 得到 IndexOutOfBoundsException。

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


【解决方案1】:

编辑:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2023-03-20
    相关资源
    最近更新 更多