 # Having one sprite move at a different speed?

Link to student project - https://studio.code.org/projects/gamelab/k2wihUbNzxhonLQw5t5_6b2A2NQC5ztN0WCYhH7Xvq4

Student wants the blue alien (var alien) to pop up at random locations. However, currently the alien is moving too quickly as the location changes with every loop.

She would like to have the alien stay in one place for a second or two then move to a new random x,y.

We’ve played with world rate, but that controls rate or the entire loop, so everything slows down. Is there a way to have an action happen every 10th loop?

Good question! I was able to find a solution, however, it does involve using a block that isn’t quite in the code.org blocks, so I will explain.

There is a math function called “modulus” which you can use to return the remainder of a division problem. For example, “10 modulus 3” = 1 (ie. 10 divided by 3 has a remainder of 1).

In many computer languages including javascript, modulus is represented by a % symbol, so:

``````10%3=1
``````

Now, how it comes in handy in this program is for us to create a variable (I called mine loop). I set it equal to zero at the beginning of the program. Then, each time the draw function runs, I add one to the value of loop and then do a math problem to see if loop divided by 10 has a remainder of 0. That runs when loop is 0 and it runs again when loop = 10, 20, 30, etc.

My changes to your program can be found at the link below. You will notice I created the variable on line 10 and I added new code on line 43 (add 1 to the loop variable which happens every time the draw function loops) and on line 44 which checks to see if the remainder of the division problem is 0 and if so, moves the alien).

Although there isn’t a % block in the toolbox, if you type the following inside the if block, it will convert into an orange block that looks like all of the other math blocks and it will work:

loop%10==0

If you want to change the frequency, changing the 10 to 15 will make the alien move less often and making it smaller than 10 will make it move more often.

Hope this makes sense, but if not, feel free to respond and I can try to explain it better.

Here’s the link to the project: Random Alien Movement Game

Happy coding!

Mike

1 Like