Games with Sam

Intercepting Sprites

Make a sprite intercept another sprite with math!

By: Chris Saylor | December 15, 2023 • 2 minute read

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.

Assumptions

To start, we’re going to have two sprites, one called Ship and one called Evil_Pizza.

Sprite setup

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 (-45,112).

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.

Advanced Applications

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:

Alternatives

If you have some javascript coding experience and are feeling adventurous, there is an extension that adds these sorts of vector operations to MakeCode Arcade directly3.

References

  1. Microsoft’s MakeCode Arcade
  2. Vectors
  3. MakeCode Arcade extension can be added to your pxt editor, however this extension is not officially approved.

Related Content