Amazing 3D Sprite Layering 🐱 | How to quickly depth sort sprites in Scratch

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello fellow scratchers today i have something really special for you look at all these cats there's so many that by the end you can't even see their faces but what is nice is that they are ordered from back to front giving you that feeling of a crowd of cats indeed take away that ordering and we are left with a complete jumble a mess of cats hold on they're few add back the layered ordering and everything is good again we know these cats are all standing one in front of the other here's another less crowded but far more dynamic scene you'll see the characters walking behind the trees but don't be fooled into thinking these trees are simply always in front of the other sprites because watch as we drag this nano character in front of a tree and then yes behind a tree how cool is that it looks so natural that you'd be forgiven for not even noting what is happening in simple terms a sprite that is further down the screen is displayed in front of any sprite that's above them on the screen this effect is applied to everything even the trees can be moved around and then correctly reshuffle in front or behind the other sprites as needed i'm sure we could have a lot of fun with this and i bet just seeing this is triggering all sorts of the fun game ideas that you could be making with this right to be able to make this work we need a lot of control over the layering of the scratch sprites more so than scratch appears to easily provide us with but thankfully i have devised a very cunning technique that is both super fast and easy to use yes it's so good and i'm going to teach it to you today and just in case you were wondering here are a few other projects that make use of this technique my initial depth sorting project the fibonacci sphere project i love that one and then there's my don't starve test project similar to what we are creating today but even projects like apple make use of this technique to ensure all the sprites initialize in the right order before the game begins so man this is so useful have i sold this to you i hope so yeah let's get scratching we can start with a fresh project but to save you looking at this boring white background let's fancy this one up a bit click on the stage and enter the backdrop editor i'm going to choose one of the preset backgrounds the one i have in mind is the simple stripes one here i'll ungroup it and then fill in the two sections separately to give a very pleasant green grassy effect there that's better and now we can proceed so clicking back into sprite 1 we need ourselves a few more cats when green flag clicked repeat 3 and create clone of myself this will make three new cats for scratchy to play with but just to ensure they are spread around the screen when they appear bring in a when i start as clone hat block and pop in a go to random position there nice let's also size scratchy up a bit use a set size block after the green flag and set size to 150. we can run the project now by clicking the green flag so we have four cats the original sprite and three clones how can we tell which one is the original sprite just click on the sprite in the sprite palette down here and scratch will highlight them on the stage there that's the one okay to help us talk about sprite ordering i'm going to shuffle them into a line so in scratch to move a sprite in front or behind other sprites or their clones all we have are these two blocks the go to front to back layer and they go forward backwards a number of layer blocks i can tap the go forward one layer to shift the current sprite forward one layer moving it in front of the sprite ahead of it like so so what is the problem then well although we can tell scratch how far to move forwards or backwards and can see the effect on the stage ourselves we don't have any way in our code to know which sprites are in front of the others or what layer they're on at all no we are rather in the dark and this is unfortunate we could really do with this information is there really no way to find this out well maybe there is make a variable named order now it's very important you mark this for all sprites okay so we'll start by setting order to one next up we want a broadcast and make a new broadcast message of order sprites we can always be hopeful right now bring in a when i receive order sprites this will trigger for sprite 1 and all its clones so if we say and pop in the order variable then clicking on the top script here will make all four sprites say well one because that's what we set order to so not useful thus far but hang on there and here's where things get interesting place a change order by one after the say block running the top script again and suddenly each sprite is reporting its own number now perhaps you were already expecting this after all we know that these broadcast events do actually run one after the other so the value of order now increases before the next cat gets to say its order value we can tell which one ran first because it has the number one yes it was this one here the one at the front of the other sprites the next one is the one just behind hmm interesting that the numbering is in order from front to back is that a coincidence do you think well easy to test we just drag one of these cats in front of the others and then run that top script again now would you look at that the one we just brought to the front is now reporting number one indeed each time we reorder these scripts and rerun the script the order of these numbers always reflects the order of the sprites from front to back amazing we have found a way to find out the order of the sprites with just using a broadcast and some variable as long as it's for all sprites as the value needs to be carried from one sprite to the next for this trick to work so this is a good start now we need to know which sprite is supposed to be in front of another so that we can shift them into the correct order once more how do we know which should be in front of the other well for now we can use each sprite's y position any sprite that is further down the screen should be moved in front of the sprites higher up the screen just like they are right now so stop right there all we have so far is the order number of each sprite how are we going to compare y positions between clones and other sprites that's a very good question i'm glad you asked we need more information than a simple old order variable can give us but what can store more than a variable it's time for an upgrade let's make a new list now this is going to store the y positions of sprites but in reality it's storing the depths of the sprites or how far into the screen they are this is often referred to as a sprites z position and since this is for sorting we'll name the list zed order it's important once more to make this for all sprites just like with the order variable we need to reset the list before we broadcast each time so delete all of z order then when each sprite receives the order event we now add thing to z order but do it right at the top before we say anything what we'll add to the list is the y position of the sprite for now we'll replace this say order variable with a say length of z order now be careful here i'm going to delete the order variable altogether which if you watch the scripts it removes any blocks that are using that variable see all cleaned up so what will this script do differently than before click the top script to run it right obviously the list has been filled with y positions that's new but what isn't different is that each sprite is still saying their layer order one through four how does this still happen without the order variable well each cat is now reporting how many items there were in the z-order list when they ran their script so obviously the first cat has just one value their own y position so it says one the second cat though can see the first cat's y position plus its own so they say to this continues for all sprites until the last cat can see all the y positions and the list is full now at present the list of y positions is nicely ordered from lowest to highest numbers but equally our sprites are ordered correctly from front to back if i was to jiggle the sprites out of order on the stage and then run the top script once more we can see not only are the cats out of order now but so is the order of the y positions in the z order list and therein lies a possible solution if we can work out how to reorder the list from lowest to highest maybe we can also reorder the sprites from back to front at the same time wouldn't that be a thing so who knows how we can sort a list of numbers in scratch let's start with just three cats on the stage with y positions of 10 20 and 30 respectively only man they are ordered back to front we want the cat with the lowest y position of 10 to be displayed in front of the pack so bring in our z-order list let us simulate how the script will run to make it easier since the scripts run on the front most sprite first i'll hide the back sprites from our diagram until they're needed the first and topmost sprite has a y of 30. all we do is add the number into our z-order list like so nothing more to do at this time so the next sprite back gets to have a go at running some scripts too this one has a y of 20. now previously we were just adding this to the list like this but now we are wanting to order this list from lowest to highest so 20 should not be below 30. so instead let's push it up to the row above better and at the same time and this is the fun bit we do the same action with the second sprite on the stage moving it forward by one layer wow nice both the list and now the sprites are in order thus far anyway and now we can proceed onto sprite number three here it is just behind the other two sprites with a y of ten question is does ten belong at the bottom of the list no sorry it's smaller than 30 so shuffle it upwards and the sprite 2. but look it's also smaller than 20. so shuffle it up again right to the top so now we have moved the last sprite forward by two layers not just one and the job is complete all our sprites are in order how awesome is that now to code this we just need to follow the same pattern but remembering it needs to run really quickly we will make a few optimizations firstly there's no need to move a sprite forward multiple times when we can just wait until we know how many layers we need to move it and then move it forwards multiple layers in one go secondly we are going to turn the list upside down on its head so rather than adding the items to the bottom of the list and scanning upwards we will start looking to insert new rows at the top of the list and search downwards instead this sounds more complicated but it actually simplifies the scripts quite a bit so do you want to join me and have a stab at putting this together in code oh boy yeah well we are certainly going to have to do some looping so we'll need a custom block for the task make a new block naming it order sprite by with a numeric input of z position and then tick the run without screen refresh this is a must as it makes sure the whole script will finish running before the next sprite runs its script without this the whole idea won't work so do make sure to check it let's rearrange the code to use the new custom block move the scripts from the when i receive order sprites into the custom block and replace them with a call to order sprite by pull the y position out of here and use it as an input to the custom block later on we will want to experiment with other values in here other than the y position so this is a nice easy way to make that possible now pop the actual z position input variable into the add block in place of the old y position cool so apart from a rearrange this should have made no difference to how our scripts run we can quickly confirm this by moving a sprite and clicking the old topmost script again to run it no difference good we are ready to begin then so yeah this script here was good for testing but we have bigger plans for it now move it out of the way we want to code up the steps that a single sprite will take to order itself rather than imagining how this will look for the first and topmost sprite let's instead assume we are one of the bottom sprites and the z-order list is already full values so we have the z-order list and we also have the sprites zed position now we must look through the z-order list to find out where it belongs make a new variable simply naming it i will use it to keep track of which item in the list we have looked at it can be for this sprite only set it to one the first item in the zed order list now to loop through we'll actually use a repeat until block the list is already ordered with the largest numbers at the top and the smallest numbers lower down so we are looping through until we find the first item less than our z position variable that will indicate where the new value belongs in the list to keep it ordered so repeat until our z position is greater than item i of the zed order list that's the same as the item of list being less than z position i just flipped it then in the loop just change i by one to keep us moving on to the next item until it's found now you may be crying hold on what if we reach the end of the list and we never find an item less than the z position will this loop never end well luckily we can check this to confirm when you ask for an item past the end of the list scratch will give you the empty value and a nice property of the empty value is that every other value is counted as greater than it so this repeat loop will always end once it reaches the empty value this was a clever optimization to avoid adding more code but there are more things to consider we haven't thought what should happen when two sprites have the same z position at present by using a greater than here any sprite at the same level as another will end up shuffling back and forward a layer rather than staying put that will be quite ugly so perhaps we want to use a greater than or equals here hmm writing two comparisons means longer code but luckily it just so happens that greater than and equals is the same as saying not less than so we can replace this with not z position is less than item i of z order that's right it means just the same thing so are you still with me i hope so we are almost there we now need to insert into the z-order list the value of course is the z-position input variable but where in the list do we insert well wherever the i variable stopped phew oh my goodness what a ride that felt more complex than it looked something to really get your head around i think before we finish it off though let's give it a quick test scroll up to the top scripts although we've not done any sprite ordering we should have at least managed to sort our z-order list clicking the script now hey would you look at that it has worked the list values are now sorted from highest at the top to lowest at the bottom that's really satisfying and a trick that not many scratchers can say they've accomplished so if you got this far then you are doing extremely well well done you have successfully coded insertion sort all that leaves us with is a job of shifting the sprites themselves forward on the stage to match how we inserted the values into this list we start with a go forward one layer block so the distance into the list that we inserted is given by this i variable but if you think about it when i is just one we are actually saying we are already at the right layer and don't need to move forwards so rather than going forwards by i we must go forward by i minus one instead yeah that seems about right i'm thinking we can test it again scrolling back up and click the top script to run it drumroll please pow would you look at that the sprites just instantly snapped into the correct order just like that i can't tell you how excited i was the first time i got this trick working it's really quite something but we should test this some more now i should have done this a while ago i'm going to attach a when space key pressed to the top script so i don't have to keep clicking it let me shuffle these up a bit are you ready press the spacebar and wham they are sorted from back to front once more superb again this is too fun no matter where they are this just works we need to push this test a bit harder let's up the clones to um 200 this will be crazy now how long do you think it will take to sort all these sprites 10 seconds 5 seconds 1 second pressing space now click wow they didn't take any time at all and we have perfect results it's a beautiful crowd of scratch cats i'm going to just drag a few of these back out of order just to confuse it space key oh gosh so quick and all the cats accounted for splendid so the difficult job is most certainly done the next thing to consider is how to use these scripts in our projects we may want to order our sprites just once when the game begins our scripts would work great for this but sometimes our sprites move around layers during gameplay and in this case we might require the ordering to occur continuously let's experiment with that we are left with just these few scripts then and only these two on the right are the important sorting scripts these scripts will need copying to every other sprite that we want to include in our ordering that often means every single sprite in the project in fact but luckily it really is just these two scripts so not a big deal that leaves this script the one that triggers the sprite ordering as such it doesn't want duplicating into every sprite in fact we often only want this in one place to make that clear i'm going to move mine into the stage sprite to complete the move delete the script from sprite1 so now we can click into the stage and let's switch this around trigger off a forever loop when green flag clicked loop forever and we delete all from our z-order list and broadcast order sprites and that's it this will keep everything ordered for as long as the project is running now watch this if we run the project with the green flag do you see what's changed previously these new scratch cats were appearing layered randomly all over each other but now they are cloning and appearing depth sorted right from the start that's crazy cool i think we can have even more fun with this by making the sprites draggable look under the sensing category for the set drag mode to draggable block we can pop one right at the top under the green flag this will allow us to drag the sprites around on the stage even in full screen mode nice run the project let me grab a cat and slowly drag them around now that's something new do you see what's happening here as i drag the sprite back and forth all the sprites are switching order to ensure the cat is layered correctly and it's happening continuously all the time and it's lightning fast surely impressive that this works with so many clones involved but it's also a little bit hard to see clearly what's going on cutting that back down to 10 cats and now as i drag this cat around you can clearly see the reordering in action yeah it just works before we continue we should just speed up the initial cloning of the cats make a new block naming it clone ticking the run without screen refresh move the cloning repeat loop in there great and make use of the new clone under the green flag just test that a few times great that starts up much snappier now with the ordering taking care of itself i really want to make this project a little bit more fun let's add some motion there's nothing new or complex here under the when i start as a clone drop in a forever loop oh but before we move anywhere we just need to point in a random direction i'll choose a random value between negative 180 and 180 that's any direction in a full circle then in the loop just move forward by two steps we run the project oh good grief what a mess not quite what i intended let's tidy this up firstly if on the edge bounce we need to keep the cats on the stage and secondly we need to keep those cats upright set their rotation mode to left right cool run the project again there that's better they're doing the cat shuffle and the important thing is they are keeping perfectly ordered from back to front with no extra work gotta be pleased with how easily this is working for us now i know i am next up i want to show you how to work with other costumes and sprites we'll need a little bit more room on the stage first so reduce scratch cat to a size of just 60 now good start by duplicating this sprite for ease that way we have those two ordering scripts for free click into the costume editor and i'm going to choose a new costume from the library there's a nice tree in here somewhere we don't need these other costumes so i'll clear those away there that's not a bad size on the stage for a tree so i'll leave it be now one thought i have trees don't tend to walk about so perhaps we can remove this forever loop from the tree sprite okay everything else can stay the same all we have are the setup scripts and the two sprite ordering scripts so simple so let's try this out right right this is looking almost right i can see the reordering happening and yet there appears to be errors look here if i grab this scratch cat and then move them in front of one of the trees do you see the tree is popping in front of the cat before it should [Music] how can i tell well it's scratchy's feet as long as scratchy's feet are below the trunk scratchy should be in front of the tree but as soon as the trunk is lower the tree should be in front but this is not the case and the reason this is an issue is that all our ordering has been based on each sprite's y position which is generally the center of a sprite's costume we need to move scratch cat up so that his feet are level with the center mark of the costume canvas now click into the tree sprite and do the same with the tree costume making the bottom of the tree trunk level with the center mark of the canvas great now we can run the project again and does this look better oh yes much better let's add a few more cats if you go down in the woods today you're sure of a big surprise yes indeed for every scratcher that ever there was is mingling there for certain because well griff patch said so i love playing with this but let's try less cats and more trees oh gosh that's quite scary who knows what they are up to in there the upshot of this is that you really should try anything and everything now because the fun is quite literally endless i am going to add a little chicken costume to the scratch cat sprite making sure to keep their feet on the middle point of the canvas course and then clone them in the scripts by duplicating the change costume loop i want loads of chicks oh yeah oh would you look at this it's too cute imagine the game you could make out of this one thing i'd like to change is that they all appear to be moving up and down the screen faster than left and right this is simply because our brains see perspective and think the ground is sloping away from us and so up and down movement is perceived as faster even though it's the same speed really let's change the when i start as clone script the point in direction change it to 45 to 135 that's diagonalish to the right but then if a random number between 1 and 2 ends up to be 1 then we'll flip the direction to the left using a turn by 180 degrees run the project again yeah i like that less crazy up and down movement so how many of you spotted the odd chick out can you see them yeah there they are all alone and not moving anywhere that's just because we're only moving the clones not the original sprite i feel sorry for it let's fix that in the when flag clicked script drop in a show just before we clone the sprites and then a hide just afterwards okay are they gone yeah of course they are so play play play with this there's a whole bunch of fun ahead of you and you simply must post your creations to the studio for this tutorial linked under the video because i can't wait to see them we are almost done here today but before we end i just want to cover one more concept that will be very handy in projects using these ordering scripts and that is what to do with sprites that you want to appear in front of everything on the stage or that have a fixed layering this is super easy so for example i can make a new sprite and i'll design a quick menu button and behold it does in fact stay right in front of everything else that is until you move one of the reordered sprites in front of it and then it all goes a bit to pot but fear not all we need to do is take the two ordering scripts the order sprites by custom block drag it into the new sprite and the when i receive order sprite script drop that in too now it has already started ordering but if we go into the button sprite scripts what i want to do is bring this button in front of everything else so we aren't going to order by the y position this time you'll see the sprite has already leapt into the front but to be more specific we can add a number in here remembering lower numbers bring sprites further forward so stuff in something like negative 1000 that will bring the button right to the front of all the other sprites and it's useful to note that positive 1000 has the opposite effect of sending the sprite behind all the other sprites right to the very back we can add any number of these kinds of sprites here's another and note while they both have the same z position number of minus 1 000 whichever is left in front remains in front like it would in normal scratch coding but if we want to force one in front of the other just change one's number to say negative 1001 that forces the button in front of the negative 1000 button and so on in this way you could assign each of your sprites its own number and then use this order broadcast to start them up in exactly the order you want them every time yeah these simple ordering scripts solve so many problems and open up so many exciting opportunities for our scratch projects what are you going to make with this let me know in the comments under the video well i do hope you've enjoyed this video smash the like button to let me know and don't forget to subscribe to the channel so that you don't miss any future exciting episodes if you want to support this channel further then you can join the griff patch channel membership to unlock those cool channel emoji get priority replies in the comments early access to videos and if you are an educator or parent you may like to go to the next level and join my inner circle where you even get the scratch projects themselves so until next time have a great week ahead and scratch on guys [Music]
Info
Channel: griffpatch
Views: 89,902
Rating: undefined out of 5
Keywords: scratch coding, scratch coding games, scratch programming, scratch game, scratch 3, griffpatch, griffpatcho, scratch, coding for kids, block coding, block coding tutorial, coding for beginners, programming, how to make a game in scratch, scratch 3d, 3d, scratch tutorials, sprite
Id: bxjbYJLAUYU
Channel Id: undefined
Length: 32min 26sec (1946 seconds)
Published: Sun Nov 28 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.