With a renewed interest in Microsoft’s MakeCode Arcade1, Sam went to work on a new game. He was happily drawing his backgrounds and sprites with a sprinkling of controls and logic, when he asked me to help him with something.
It seems he had some “evil” pizza slices that he wanted to have come straight at the player randomly from the top of the screen. I have to admit, I wasn’t immediately able to call forth the vector math from ninth grade pre-calculus in the heat of the moment.
Luckily, the internet is a great resource for math and after some googling2, I found a good primer on vectors. To spare other parents who may be asked a similar question as I, let’s walk through how to make this happen.
To start, we’re going to have two sprites, one called
Ship and one called
Basic Vector Math
MakeCode arcade uses a two-dimensional coordinate system for moving around sprites. We know the position of the player and the “evil” pizza.
First we need to find the vector between these two points. By subtracting the position of the sprite we want to intercept from the position of the sprite that is doing the intercepting, we can get a directional vector to send the sprite.
In our example, this would produce an array of values
Setting our “evil” pizza sprite’s velocity to this vector will cause the pizza to intercept the ship.
The above is interactive, try to avoid the evil pizza.
The above works, but it gives little control with how fast or slow the “evil” pizza approaches the ship.
We can improve on this by calculating the unit vector.
First we start with getting the magnitude of the intercept vector:
Now, calculate the unit vector by dividing the intercept vector by the magnitude:
Having the unit vector allows us to easily scale the vector to a more granular level simply by multiplying it by a new magnitude (speed) value.
You can see a full working example here: