How can i combine a random made background with a moving Object without redrawing?

Hello i am trying to make a starsky where i generate the background and the positions of the stars randomly.

I now want to make some fallen stars currently trying todo it with arrays.
The problem is that it always redraws it in the draw() function.
And i cant find a way to solve that problem.

Because i cant generate it in the draw function randomly because the screen woud go crazy then…
Hope you understand my question and someone can help me!

1 Like

Processing.org/reference/createGraphics_.html

2 Likes

Does not work for me, i cant call the method drawg() in the draw function and the background is also not the color i picked

PGraphics pg;

void setup() {
  size(800,600);
  pg = createGraphics(800,600);
  
       
}

void draw() {
  pg.beginDraw();
  pg.background(23, 14, 133);
  pg.drawg();
  pg.endDraw();

}


void drawg(){
   for (int i=0; i<20;i++){
    noStroke();
     fill(random(17,30),random(9,19),random(125,140));
     ellipse(random(0, width), random(0, height), random(40, 350), random(30, 300));
   }
 
   for (int i=0; i<250;i++){ //random Stars
     float w = random(width);
     float h = random(height);
     fill(255); 
    // noFill();
     ellipse(w, h, 3, 3);
   }
}
1 Like

Using arrays is a good idea, especially a PVector array, because it can hold the x and y values.
Here is an unfinished code for you start with. You will have to change it in a way that the shooting star will fade away.

int ns = 20; // Number of stars
boolean star_fall = false;
PVector[] stars = new PVector[ns];

void setup() {
  size(600, 600);
  frameRate(10);
  initStars();
}

void draw() {
  background (0, 0, 80);
  for (int i = 0; i < ns; i++) {
    fill(random (50, 160));
    circle(stars[i].x, stars[i].y, 5);
  }
  if (star_fall == true) {
    PVector random_star = stars[int(random(ns))];
    for (int i = 0; i < 10; i++) {
      random_star.x += 10;
      random_star.y += 10;
      fill(255);
      circle(random_star.x, random_star.y, 5);
    }
    star_fall = false;
    initStars();
  }
}


void mousePressed() {
  star_fall = true;
}

void initStars() {
  for (int i = 0; i < ns; i++) {
    stars[i] = new PVector();
    stars[i].x = int(random(10, width-10));
    stars[i].y = int(random(10, height-10));
  }
}
1 Like