In the previous blog, we covered how to make the sprite jump, and this is what our script looked like:
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
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.
Getting back to the script we started with, change the first glide block to:
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:
Combining all the steps above, here is the final block simulating a sprite jump, 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.