Issue
I wanted to ask if you have any ideas on how to solve my problem? What i am trying to achieve is moving things in a direction but keep spawning instances in set y-position
public class Balony extends Canvas {
Group root;
GraphicsContext gc;
Timeline t;
Scene scene;
int poz = 100;
Color farba=Color.RED;
Random rand = new Random();
int rychlost= rand.nextInt(20 - 2 + 1) + 2;
public Balony(Scene scene){
super(800,1000);
this.root = root;
this.scene = scene;
gc = this.getGraphicsContext2D();
setLayoutY(100);
t = new Timeline(new KeyFrame(Duration.millis(100),e->chod()));
t.setCycleCount(Animation.INDEFINITE);
t.play();
}
private void kresli(){
farebnost();
spawn();
gc.setFill(farba);
gc.fillOval(poz-40, scene.getHeight()-100, 80, 100);
gc.setFill(Color.BLACK);
gc.fillRect(poz, scene.getHeight(), 2, 100);
}
public void chod(){
kresli();
setLayoutY(getLayoutY()-rychlost);
}
public void spawn(){
int miesto = rand.nextInt((int) (scene.getWidth() - 50 + 1)) + 50;
poz = miesto;
}
public void farebnost(){
int colour= rand.nextInt(10 - 1 + 1) + 1;
switch (colour) {
case 1: farba = Color.RED; break;
case 2: farba = Color.GREEN; break;
case 3: farba = Color.BLUE; break;
case 4: farba = Color.YELLOW; break;
case 5: farba = Color.ORANGE; break;
case 6: farba = Color.BROWN; break;
case 7: farba = Color.YELLOWGREEN; break;
case 8: farba = Color.ORANGERED; break;
case 9: farba = Color.HOTPINK; break;
case 10: farba = Color.VIOLET; break;
}
}
This is a simple program I made to explain my problem, when new balloons are spawned their y-position is moving upwards but I want to keep the new instances down + make them move up at different speeds (I do believe this is solvable by moving the entire process of movement into my spawning void so this is not as important).
Solution
- You need to introduce a class for a single balloon which will store it's position, speed and colour. Let's call it
Balon
. - Inside class
Balony
, you should storeList<Balon> balony;
- At the end of
chod()
method, you should loop throughbalony
, and update the position of eachBalon
.balon.setPoz(balon.getPoz() + balon.getRychlost());
- Other methods (for example
kresli()
) will have to change accordingly, to paint a list of balloons, instead of the single balloon
Answered By - Alan Rusnak