Good Coding Practice: Using Relative Coordinates

In the previous blog, we covered how to make the sprite jump, and this is what our script looked like:

Sprite Vertical Jump with Horizontal Movement

What will happen every time you click on green flag? The sprite will come to the center of the stage (coordinates [0,0]) and then glide to [20,20] coordinates and then to [40,0]. Click green flag again, come to center of the stage and then jump again.

Let’s say we don’t want the sprite to come back to [0,0] every time. We want the sprite to start the jump from where it left off.

To do that, instead of using absolute values, we need to use relative values. Let’s see how can we do that…

Firstly, let’s remove the go to block, since we don’t want our sprite to come back to [0,0] every time.

Currently, the first glide block is making the sprite go to [20,20] coordinates since we assumed that the sprite will start from [0,0]. Now as we don’t want that assumption to be true anymore, we need to change the block such that the sprite covers 20 points distance horizontally and 20 points distance vertically, from the starting point.

In that case, let’s say the current position of the sprite is [x,y]; then we want the sprite to end at [x+20,y+20] at the end of first glide block.

To do that in SNAP!, we need to use 4 new blocks that we haven’t seen yet.

In the Motion palette, at the bottom there are 2 blocks: x position and y position

X and Y Position Coordinates

These two blocks are also known as reporter blocks since they report the position at any point in time. We will use these to know the current position of sprite.

Another set of blocks we will use in this sample are in Operators palette. Operators palette has many blocks that lets you use operator functions. For this example, we will use addition and subtraction block to add and subtract 2 values.

Addition and Substraction Operator Blocks in SNAP!

Getting back to the script we started with, change the first glide block to:

Using Relative Coordinates in SNAP!

Once the sprite reaches at the top/peak of the jump, we need to modify the second glide block to bring it back to the same level (or y coordinate) as its starting point, continuing to cover positive distance in x direction.

This is what the second glide block should change to:

Using Relative Coordinates in SNAP!

Combining all the steps above, here is the final block simulating a sprite jump, using relative coordinates.

Sprite Vertical Jump with Horizontal move using Relative Coordinates

Now try clicking on the green flag multiple times, your sprite will continue to jump from the position it was last at.

Share This:

A geek, a techie, a daughter, a sister and a wife. Worked at Microsoft for 8 years and currently working at Amazon Web Services (AWS). All opinions expressed here are my own and has no correlation to my employer or ex-employers!

Leave a Reply

Your email address will not be published. Required fields are marked *