My code's not working how I want it to

I’m trying to make a loading screen-adjacent extension, and the loading sprite is always on top of the text sprite, even when I set the loading sprite’s z. Does anyone have an idea of what’s wrong?

let changingY1 = 0
let changingY2 = 0
let changingX1 = 0
let changingX2 = 0
function loadingVertical(sprite: Sprite, speed: number, color: number, x1: number, x2: number, z: number) {
sprite.setFlag(SpriteFlag.RelativeToCamera, true)
for (let index = 0; index < 120; index++) {
sprite.image.drawLine(x1, changingY1, x2, changingY2, color)
sprite.z = z
changingY1 = changingY1 + 1
changingY2 = changingY2 + 1
pause(speed)
}
changingY1 = 0
changingY2 = 0
sprites.destroy(sprite)
}
function loadingHorizontal(sprite: Sprite, speed: number, color: number, y1: number, y2: number, z: number) {
sprite.setFlag(SpriteFlag.RelativeToCamera, true)
for (let index = 0; index < 160; index++) {
sprite.image.drawLine(changingX1, y1, changingX2, y2, color)
sprite.z = z
changingX1 = changingX1 + 1
changingX2 = changingX2 + 1
pause(speed)
}
changingX1 = 0
changingX2 = 0
sprites.destroy(sprite)
}
//% color="#1F7EC7" 
//% icon="\uf110"
namespace Loading {
/**
 * Creates a vertical loading screen using the inputted settings.
 */
//% block="make vertical loading screen with speed $speed and color $color on z $z"
export function loadingScreen1(speed: number, color: number, z: number) {
let loadingSprite = sprites.create(img`
`, SpriteKind.Food)
loadingSprite.z = z
loadingVertical(loadingSprite, speed, color, 0, 159, z)
}
/**
 * Creates a horizontal loading screen using the inputted settings.
 */
//% block="make horizontal loading screen with speed $speed and color $color on z $z"
export function loadingScreen2(speed: number, color: number, z: number) {
let loadingSprite = sprites.create(img`
`, SpriteKind.Food)
loadingSprite.z = z
loadingHorizontal(loadingSprite, speed, color, 0, 119, z)
}
}

@richard, do you know what’s wrong?

@Blobbey can you share your whole project, not just the extension code? I don’t see any text sprites in the code you posted.

2 Likes

Here you go!

Thanks! Your issue here is that you’re pausing in your extension code, so the text sprite isn’t actually getting created until the loading bar finishes. The z-index is working properly.

There are two possible fixes here:

  1. Simply move your text sprite creation above your call to your loading function

  2. In your extension, wrap your functions inside a call to runInBackground like so:

    control.runInBackground(() => {
        loadingVertical(loadingSprite, speed, color, 0, 159, z)
    })
    

    …but that’s probably not what you want, since then you wouldn’t be able to know when the loading finished

3 Likes

Okay, thank you so much!