Scratch for Kids

A Watch the course on Frontend Masters

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.