Okay, also mache ich ein Spiel, in dem es Hunde regnet. Ich habe die Hunde mit einem Array erstellt und sie mit einem neuen Thread zu meiner Hauptklasse hinzugefügt und alle außer den Hunden bewegen sich nicht und ich kann nicht herausfinden warum. Kann mir jemand helfen, meinen Fehler zu erkennen? (Hinweis: Dies ist keine Hausaufgaben, ich tue dies mit meiner Freizeit)Java - Array von Objekten bewegt sich nicht
Hier ist ein bisschen mein Code: Hauptklasse:
// 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");
}
}
Hunde Klasse:
// 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);
}
nur durch einen kurzen Blick nahm, keine wirkliche Analyse ... aber '-Größe/2' scheint, wie es ein Problem sein könnte . Meinst du "--size/2' oder' (-1 * size)/2'? Und lol @ 'doggo' –
Ich denke, das Problem ist, dass Sie UI-Code auf einem Nicht-UI-Thread ausführen, nicht wahr? – Sweeper
Es ist nicht das Problem, nach dem du suchst, aber ich verstehe nicht, wie du keine IndexOutOfBoundsException vom Zugriff auf 'doggo [4] erhalten hast, wenn' doggo' nur 4 Elemente hat. –