Would you like your students to create a monster that moves around the screen randomly? We can easily do this with a loop that uses the “If on edge, bounce” block; but for more randomness we can make it move in even more random directions.
Just add a “Monster” sprite and give it the following code:
What’s happening here? Well, we are just checking that when our character touches the edge of the screen we move it back away from the edge, then we have it move off in a random direction. It’s ok if it goes towards the edge again, eventually it will move off somewhere else.
Want to combine this moving with animating a costume. This is not as easy as it might seem. Adding a “next costume” block to the code above doesn’t quite cut it! Often our sprite will get stuck on the edge of the screen and we don’t want that. (This is because often when we detect the edge and rotate to a different costume it flips to still touching the edge and might go off even further out of reach).
To make this work in a predictable way, I made my sprite change direction only based on its x-y position instead of detecting edge collisions. The following code may look a little intimidating but it’s just checking all the different edges that we can run into via coordinates this time so we have to have 4 different cases. (And I added a random starting position for good measure). Our boundary variable can be changed based on how close we want our monster to get to the edge.
And we end up with something like this!
Learn more about Itch here: https://www.itchcode.com