Unit 3 Lesson 11 Order of Sprites

My student is trying to get sprite1 to be drawn behind the background with sprite2 appearing at the forefront of the screen.
When drawsprites is called before sprite2, sprite1 appears in the correct place, but sprite2 isn’t drawn. When drawsprites is called after sprite2, sprite1 jumps to the front of the background.
We’ve tried moving the placement of drawsprites and changing the order of background and sprite1 and sprite2.

Hello @aschoolland ,

When I run the code, this is what I see. Sprite 1 (the robot) is behind sprite 2 (the bug).

This appears to be what you wanted or am I mistaken? Did your student figure something out after you asked the question?

Screenshot 2023-09-26 at 4.27.46 PM

One suggestion I do have is to move the “Create sprite” block out of the draw loop. All Create sprite blocks should be at the top of the code. If they are inside the draw loop, it is creating a new sprite every time and that can have unintended consequences.

If it still isn’t working correctly, please let me know and I’m happy to keep helping.


The code is out of order. Check out my remix with comments and see if it helps.
Some very common errors here.

the background(“red”) command will literally cover over everything. You can’t make a sprite appear behind the background. You can make it appear behind a shape.

createSprite should NOT be called inside the draw() loop. it will slow the computer down because it is creating thousand of sprites variables in memory.

because of the syntax of gamelab/javascript, the only way you can draw a sprite, then a shape, and then a sprite is something like this:

var sprite1 = createSprite(200, 200, 50, 50);
shape(0, 0, 0, 400, 400, 400);
shape(400, 0, 0, 400, 400, 400);
rect(50, 200, 100, 100);
rect(250, 200, 100, 100);
rect(236, 100, 150, 10);
text(“Bzzzzzzzzz”, 265, 80);
ellipse(96, 281, 50, 50);
ellipse(300, 281, 50, 50);
var sprite2 = createSprite(200, 100, 30, 30);
function draw() {
rect(0, 275, 400, 200);
sprite1.x = randomNumber(200, 220);