Scrollen

Scrollen#

Oft möchtest du den Bildschirm „scrollen“ lassen.

The easiest way to do this is to “move” a background:

To make this work really well, you need to create the background as an “actor” and you need two backgrounds.

scrollender Hintergrund

Both backgrounds move from right to left (or from top to bottom, left to right, … - depending on the game) - As soon as a background would leave the playing field, it is reattached on the far right.

This creates the impression of an “infinitely long landscape”.

Im Code kann man dies wie folgt umsetzen:

  • Create the background twice with the same background and place them side by side.

  • It may be useful to store the backgrounds in a list, as you can then move them together.

back0 = Actor()
back0.add_costume(BACKGROUND)
back0.size = WIDTH, HEIGHT
back1 = Actor(WIDTH, 0)
back1.size = WIDTH, HEIGHT
back1.add_costume(BACKGROUND)
backs = [back0, back1]

In der world.act-Methode, die jedes Frame einmal aufgerufen wird, kannst du den Bildschirm langsam verschieben:

@world.register
def act(self):
    for back in backs:
        back.x -= 1
        if back.x <= - WIDTH:
            back.x = WIDTH

Als Code sieht dies so aus:


from miniworlds import *

WIDTH, HEIGHT = 800, 400
world = World(WIDTH, HEIGHT)
left, bottom = WIDTH/2, HEIGHT/2

BACKGROUND = "desertback"

back0 = Actor()
back0.add_costume(BACKGROUND)
back0.size = WIDTH, HEIGHT
back1 = Actor(WIDTH, 0)
back1.size = WIDTH, HEIGHT
back1.add_costume(BACKGROUND)
backs = [back0, back1]

walker = Actor((100, HEIGHT - 100))
walker.size = 100, 60
walker.add_costumes(["walk1", "walk2"])
walker.speed = 1
walker.count = 0

@world.register
def act(self):
    for back in backs:
        back.x -= 1
        if back.x <= - WIDTH:
            back.x = WIDTH
    walker.count += walker.speed
    if walker.count > 11:
        costume = walker.next_costume()
        walker.count = 0

@world.register
def on_key_down(self, keys):
    if "q" in keys:
        world.quit
        
world.run()

Note: The idea comes from the blog schockwellenreiter - Jörg Kantereit programmed this snippet with Pygame Zero there.