My week with Micro:Bit

10 thoughts
last posted Jan. 18, 2016, 11:01 p.m.

2 earlier thoughts

0

Project 2 - Bouncy Ball

In my next project I wanted to get a ball to bounce on the display. I was hoping maybe to build a game out of it later, but first I needed to get a ball to move and bounce.

I started by giving the ball x and y coordinates and then a speed for both the x and y. On each round the ball's coordinates would change based on the speed. If the ball hit an edge, the speed is multiplied by -1 to change the direction of the ball.

If the speed was more than 1 the ball quickly ended outside of the grid (and caused an error). My not entirely real world like fix was to check if the ball would be outside of the grid before drawing it, and if it would, force within the grid by settingt it to the max or min width/height (depending on where it was).

While working on this I noticed two gotchas: I had to remember to clear the previous pixel out before drawing the new one, and I had to add a sleep timer between moves or the ball would appear to be moving way too fast.

As the 5x5 grid is tiny it turns out the ball gets stuck in a rut quite easily. To counter this I added options to change the x and y coordinates using the buttons so that the ball could be moved to a new trajectory.

I also added a function to add a new ball to the mix by clicking both buttons. It turned out the more balls I added the slower it all got. I did my best to counter this by reducing the sleep time for each new ball added to the mix. I also made the maximum number of balls to be 4 -- after that trying to add more ends the program.

You can find the source code here. Unfortunately I didn't get a video of this as poor Mei-Xiu broke down before I remembered to video this one, but just imagine an awesome little ball bouncing around like crazy. (Or just run the code and see what happens.)

Edit

Now that Marja is here, I was able to get a video of this program.

7 later thoughts