Background change on Run

I have a student who is just starting her project and she wants her background to change every time she hits the run button. Is there a way to do this?

Hello @langilla1,

this is possible but it depends on what background your planning to set

Here’s a demo showing both random Solid & Image Based backgrounds

// Solid color demo
var rgb = [randomNumber(0, 255), randomNumber(0, 255), randomNumber(0, 255)];
/* 
    this works however only because the function tests for this case 
    youd have to use this otherwise 
    EX:
    background.apply(this, rgb);

    that would accurately fill in the arguments for a specific function
*/
background(rgb); // this would go in the main loop

// Image based backgrounds
var bgs = ["bg1", "bg2", "bg3", "bg4"]
/*
    random is able to choose from array values as well
    however this won't help the student to understand whats going on
    what it's doing is selecting an index from the length - 1 of the array
    EX:
    var bgImg = bgs[randomNumber(0, bgs.length - 1)];
    
    this is what the random assignment method is doing because it has a test case for it
*/
var bgImg = random(bgs); // you'd set the sprite to this to display it as a background
var bg = createSprite(200, 200);
bg.setAnimation(bgImg);

hopefully this clarifies it

Varrience

2 Likes

@langilla1,
Another way to do this using the blocks is to set a variable to a random number from 1 to the number of backgrounds and place this above the draw loop. Then, inside the drawLoop, if the number is 1 = setAnimation for the background to background 1. If the number is 2 = setAnimation for the background to the 2nd background etc. Here is a simple example.
Best wishes!
~Michelle