Javascript, which App Lab is based on, is call by value. Meaning that when you call a function like timedLoop
the value of the variables are sent as parameters to the function and not a reference to the variable. When you send the variable itself as a parameter that is call by reference.
So, call by value only sends the value. If you change the value of the variable it doesn’t do anything because timedLoop
has the old value. timedLoop
doesn’t know nor care about the variable speed
.
What you need to do is stop the loop and start it again after you change speed
. Look at this for example:
var score = 0;
var lives = 3;
var bugSpeed = 1000;
onEvent("image2", "click", function() {
lives = lives - 1;
setText("lives_lbl", lives);
if (lives < 1) {
stopTimedLoop();
setScreen("screen2");
}
});
onEvent("bug", "click", function () {
score = score + 1;
setProperty("score_lbl", "text", score);
if (score % 3 == 0 && score > 0) {
changeBugSpeed();
}
});
function startMovingBug () {
timedLoop(bugSpeed, function () {
setProperty("bug", "x", randomNumber(1, 299));
setProperty("bug", "y", randomNumber(50, 400));
});
}
function changeBugSpeed () {
bugSpeed = bugSpeed * 0.8;
stopTimedLoop();
startMovingBug();
}
startMovingBug();
First, I changed speed to bugSpeed because you found a bug in App Lab. Nice.
I made the startMovingBug
function. I can use this to start the bug up. I also moved the game-over-test to just below where the lives are set. Checking the lives right after you change them removes a little delay between losing the last life and the game over screen. But more importantly it takes the game over logic out of the timed loop so the timed loop code is easier to understand.
I made the changeBugSpeed
function which changes the speed, stops the previous loop, then starts a new loop but moving faster.
At the bottom of the code I added a call to startMovingBug
to start the game going.
Functions are your friends let them help you.