Lesson 20, Unit 3: Cake Defender


#1

Is there a way to set the alien to not go off of the water? I can only get it so the alien walks on water. I got the ladybugs to disappear but cannot quite figure out how to set the alien to bounce off of the “water edge.”


#2

The reason you can’t use the normal collision functions is that water and bridge are just drawings, not sprite. I can think of a couple ways to approach this.

First, you could add gray or invisible sprites that match the position of the edges of the bridges. You can use sprite.setCollider and sprite.debug to make sure they go all the way across the screen in the right way. Then you could one of the collision functions like player.collide to keep them from moving past the edges.

A second approach would be to just check the player’s y position. If the players goes too high or low, just reset their y position. For example if (player.y < 140) { player.y = 140; }. This is similar to how you write the enemiesTouchWater function here: https://studio.code.org/s/csd3/stage/20/puzzle/16


#3

I have another question for this game. I have students that want to make the velocity increase by .25 every time the score goes up by two. What would the code be to make that happen. I know an ‘if’ statement will increase it once, but how do you make this an ongoing condition??


#4

There are a variety of interesting and elegant ways to approach this, but I’d like to propose the simplest way to get a similar affect. Look for any place in the code where the sprites’ velocityX is updated and replace it with something like this:

enemy1.velocityX = 2 + (score * 0.25);

This will constantly update the enemy’s velocity as a function of the score, adding two for the default state when score === 0. Hope this helps!


#5

I always tell the students, if you want to keep track of something, you need to make a variable to do so.

In this case, it seems as though you need to keep track of whether the score has increased by two.
So you could make a var that is called deltaScore and set it to zero. (before the draw function)
You need to find the place where the score variable gets changed and changed deltaScore every time the score changes as well.
Then you could write an if statement inside the draw function like

if( deltaScore == 2)
{
    
    sprite.velocityX += 0.25 ;
    sprite.velocityY += 0.25 ;
    //And then it is key here to reset deltaScore to zero so that the process can start all over again.
   deltaScore = 0 ;
}

Let us know how it goes.