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

2018/9/6

Scrolling World (Objects)

Starvader Starvader

2018/9/6

#
Hi, I am trying to create a scrolling world, where the floor moves every time the right arrow key is pressed, to give the illusion that the character is moving. Here is my code so far:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class MyWorld here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class MyWorld extends greenfoot.World
{
    private Ground[] brick = new Ground[1000];
    int y1=580;
  
    public MyWorld()
    {    
        super(1000, 600, 1, false);
        Mario mario = new Mario();
        addObject (mario, 500, 525);
        for(int i=0; i<20; i++) {
        Ground hold = new Ground();
        addObject (hold, (50*i) - 30, 580);
        brick[i]=hold;
    }
    moveWorldRight();
}
    
    public void moveWorldRight() {
    if (Greenfoot.isKeyDown("right")) {
    for (int i=0; i<20; i++) {
    Ground x = brick[i];
    int Xcoord = x.getX();
    x.setLocation(Xcoord-50, y1);
    brick[i] = x;
    if (Xcoord<0){
        x.setLocation(Xcoord+1000, y1);
        brick[i] = x;
    }
}
}
}
}

but I cant seem to get it to work. Can anyone help me out?
Super_Hippo Super_Hippo

2018/9/6

#
You have quite a lot unnecessary code in the moveWorldRight-method. However, it is called only once when the world is created (line 24). Instead, you need to call it repeatedly from an act method:
public void act()
{
    moveWorldRight();
}
(Btw, before posting, press Ctrl+Shift+I in Greenfoot to fix the indenting.)
You need to login to post a reply.