This site requires JavaScript, please enable it in your browser!
Greenfoot back
Samuaelk
Samuaelk wrote ...

2021/4/16

How can I make my background scroll left and right?

RcCookie RcCookie

2021/4/16

#
Concerning the scrolling: you can actually get away with only 2 background objects like this:
// In world constructor
addObject(new Background(), 0, getHeight() / 2);
addObject(new Background(), getWidth(), getHeight() / 2);

// In world
@Override
public void act() {
    if(Greenfoot.isKeyDown("right")) scroll(SCROLL_SPEED);
    else if(Greenfoot.isKeyDown("left")) scroll(-SCROLL_SPEED);
}

private void scroll(int speed) {
    for(Background b : getObjects(Background.class)) b.move(speed);
}

// In Background class
@Override
public void setLocation(int x, int y) {
    while(x < -getWorld().getWidth() / 2) x += getWorld().getWidth() * 2;
    while(x >= (int)(getWorld().getWidth() * 1.5)) x -= getWorld().getWidth() * 2;
    super.setLocation(x, y);
}
The world just moves the background left and right, and the background always checks weather it is within bounds. If it is not it will adjust itself and switch sides. And because the code uses "getObjects()" we don't need to save the background objects into variables / an array.
Samuaelk Samuaelk

2021/4/17

#
Thanks!
You need to login to post a reply.