How to keep a randomised y position circle the same while running code

Hi everyone, I’m able to get the y position of the circle to be randomised however it doesn’t stay in one spot. It changes the y position of the circle between (25,240) while running the code. I was trying to get the circle in a random position every time I run the code rather than it changing while the code is running. This is my current code for it. All help will be highly appreciated!

int x = 30;
int y = 60;
float gunX = x+20;
float gunY = y+20;
float circleY;
boolean bulletFlies=false;
float bulletX = 20;
float bulletY = 20;

void setup() {
size(500, 500);
circleY = random(25,480);

void draw() {
fill(255, 56, 99);
ellipse(x, y, 60, 60);
gunX = x+12;
gunY = y;

circle(450,random(circleY), 80);

void keyPressed() {
if (key == ‘s’) y = y + 8;
else if (key == ‘w’) y = y - 8;
else if (key == ’ ') {
bulletX = gunX+14;
bulletY = gunY+4;

void bullet() {
if (bulletFlies) {
ellipse(bulletX, bulletY, 6, 6);
bulletX = bulletX+5;


Please format your code by selecting it and using the </> button in the editor bar.

The draw() function is running several times per second. So if you have a random() function there it will give different values at each call of draw() so several times per second.

Setup() on the other hand only run once so a random() call there will give you a random value every time you launch your program but if you store it in a variable, it sill stay the same during the full execution.

This is already what you are doing with:

circleY = random(25,480);

But then in draw(), you have:

circle(450, random(circleY), 80);

What you program is doing is:

  1. Pick a value at random between 25 and 480and store it in circleY.
  2. At every loop, pick a random value between 0 and circleY.

I suppose that’s second step is where you don’t want to pick another random value. Instead you want to use directly the circleY variable that already contain a random value:

circle(450,  circleY,  80);
1 Like

Oh okay, thank you for helping I understand why it wasn’t working :slight_smile:

1 Like

thanks for the awesome information.

1 Like