Java - Array of objects won't move

130 Views Asked by At

Okay, so I'm making a game in which it rains dogs. I created the dogs with an array and added them to my main class with a new thread and all but the dogs aren't moving and I can't figure out why. Can anyone help me spot my error? (NOTE: This is not homework, I am doing this with my free time)

Here is a bit of my code: Main class:

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

}

Dogs Class:

// 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

There are 1 best solutions below

0
On

EDIT:

Your Dogs class needs to implement Runnable so your run() method can be called when you start the thread.

You can have a look at the oracle documentation here for an example: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html