Adding A Character To The Falling Game (Solution)
Here is a decent start that we can build on.
when green flag clicked
set rotation style [left-right v]
forever
if <key [right arrow v] pressed?> then
point in direction [90]
move [10] steps
next costume
end
if <key [left arrow v] pressed?> then
point in direction [-90]
move [10] steps
next costume
end
end
Adding the Gravity
Picoās not going to use the gravity just yet, but we can add the same falling logic that use used for the apples to Pico.
when green flag clicked
set rotation style [left-right v]
forever
if <key [right arrow v] pressed?> then
point in direction [90]
move [10] steps
next costume
end
if <key [left arrow v] pressed?> then
point in direction [-90]
move [10] steps
next costume
end
repeat until <touching color (#000)?>
change y by (Velocity)
change [Velocity v] by [-1]
end
end
Fixing a Bug: Pico Can Fall Too Far
With our currentāand super simpleāvelocity code, itās possible for Pico to drop a little too far. This is probably fine and you donāt need to worry about it. But, if you really want to know one way to adjust for this, then we could basically check to see if the next time we move Pico is about to be too far.
There are a number of ways that you can do this, weāre going to start with the simplest one. We roughly know where we placed Pico. Letās say that our floor starts at -159. I donāt want Pico to fall any further than -159. I can add this code to my repeating block.
repeat until <touching color (#000)?>
if <((y position) + (Velocity)) > (-159)> then
change y by (Velocity)
change [Velocity v] by [-1]
else
set y to (-159)
end
end
Basically, weāre telling the sprite to do the normal falling logic until weāre about to fall too far and then just cut it short and move us to the correct right position. Itās a little messy, but it works. Here is the full code.
when green flag clicked
set rotation style [left-right v]
forever
if <key [right arrow v] pressed?> then
point in direction [90]
move [10] steps
next costume
end
if <key [left arrow v] pressed?> then
point in direction [-90]
move [10] steps
next costume
end
repeat until <touching color (#000)?>
if <((y position) + (Velocity)) > (-159)> then
change y by (Velocity)
change [Velocity v] by [-1]
else
set y to (-159)
end
end
end
Again, this still isnāt our best solution since it involves hard coding in exactly where the ground is. Iāll show you how to really get this right later.
With that, letās look at keeping score.