Simple Collisions in Scratch
You've made an awesome sprite in Scratch and you've added code to make it move around in four directions. Now you want it to bump into objects in your game. But how do you do it?
Your movement code probably looks like this. If it doesn't then make it so!
when green flag clicked forever if <key [left arrow v] pressed?> then change x by (-4) end if <key [right arrow v] pressed?> then change x by (4) end if <key [up arrow v] pressed?> then change y by (4) end if <key [down arrow v] pressed?> then change y by (-4) end end
First we should create something to collide with! Make a new Sprite by clicking the paintbrush icon under the stage. Then make sure this sprite is in Vector mode. Finally, draw a block box in the middle something like this:
Now click on the little blue circle containing an i, on your new sprite. This brings up some more properties of the sprite, including its name. We should rename this to something sensible so that we can collide with it. I'm going with "Level".
Now we must add code to the player's sprite that checks for collisions with the Level sprite. The trick is to get Scratch to check for collision after it has moved the sprite in one of the four directions. If it does find that the player's sprite is touching the Level sprite then it simply moves it back to where it just came from.
when green flag clicked forever if <key [left arrow v] pressed?> then change x by (-4) if <touching [Level v] ?> then //New IF block inside the old one change x by (4) end end if <key [right arrow v] pressed?> then change x by (4) end if <key [up arrow v] pressed?> then change y by (4) end if <key [down arrow v] pressed?> then change y by (-4) end end
Look at the code that has been added, just after the first change x by -4. The new if block is inside the if block that runs when the left arrow is pressed. So this means that Scratch only runs this new if block when the surrounding block is activated.
We have nested one if block inside another.
How does this new code create collision detection?
After the sprite has moved 4 pixels to the left the code then checks to see if it is now touching the Level sprite. If it is then it moves it back 4 pixels in the opposite direction. This happens so quickly that we never see the sprite moving!
Now add similar code to the other four directions. Remember to alter the 'change x or y by' directions and values!
Here's an example Scratch project with the collision code working.