Document stub.png This article or section may not have content matching Scratch Wiki editing standards. Please improve it according to Scratch Wiki:Guidelines and Scratch Wiki:Editing Conventions. (April 2023)
Reason: Needs explanations for what the code is doing.
DocumentInQuestion.png It has been suggested that this page's contents be merged with the page Scrolling (sprites). You can discuss this on the page's talk page. (January 2023)

Scrolling in Scratch is the movement of (usually contiguous) sprites across the stage. Commonly used for platformers, scrolling text, maps in adventure games, and sometimes large pictures, it can be found in many projects. A project that uses scrolling is called a scroller.[1] In this application, scrolling is used on a background sprite for platformers as the level itself and its hitbox, therefore allowing the player to appear to interact with the background.

Scrolling

Setup

Before starting coding, make a new sprite. This will be used as a background. In the sprite make an empty 0x0 costume (create an empty costume and spam the Convert to [bitmap / vector] button) and at least one costume containing whatever you want in the background/level. In the same sprite make a custom block called Set Size with an input of size, and code it like this:

define Set Size (size)
set [prev costume name v] to (costume [name v]) // this is data that is saved before the size change starts
switch costume to ( empty 0x0 costume v) // this is so that the sprite can get bigger
set size to (size)
switch costume to (prev costume name) // the costume from before (data)

Finally, make 2 variables called scroll x and scroll y.

Code

Put this code in the scrolling sprite:

when gf clicked
forever
go to x: ((0) - (scroll x)) y: ((0) - (scroll y))
Set Size (400):: custom
end

Testing

Show both of the 2 variables and right-click them. Turn the variables into sliders. Then right-click them again and change the range from 100 to 200 and 1 to -200.

Collision

Setup

You need another sprite called "Level Hitbox" for the collisions. You also need a player sprite to control the scrolling with the arrow keys.

Code

To code the player sprite, you need to do this:

when gf clicked
forever
change [scroll x v] by ((<key (right arrow v) pressed?> - <key (left arrow v) pressed?>) * (5))
if <touching (level hitbox v)?> then
change [scroll x v] by ((<key (right arrow v) pressed?> - <key (left arrow v) pressed?>) * (-5))
end
change [scroll y v] by ((<key (up arrow v) pressed?> - <key (down arrow v) pressed?>) * (5))
if <touching (level hitbox v)?> then
change [scroll y v] by ((<key (up arrow v) pressed?> - <key (down arrow v) pressed?>) * (-5))
end
end

To code the level hitbox, use this code:

when gf clicked
forever
go to x: ((0) - (scroll x)) y: ((0) - (scroll y))
Set Size (400):: custom // use the same code as the scrolling backdrop sprite
end
Cookies help us deliver our services. By using our services, you agree to our use of cookies.