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

2012/12/10

Problem with scrolling the world?

UnclePedro UnclePedro

2012/12/10

#
Hi, I'm making a side-scrolling platformer game and I'm having problems scrolling the screen as the character moves. I figured it would be easy to do, by using getWorld().getObjects() and a for loop to set the location of each object as the character moves, but its proving to be more difficult... Below is the method I'm using to try and attempt this... I have a few ideas on what's wrong right now, but I could use a couple outside opinion on how to do this... I've seen other people do this in their code, but it looked much more complicated than I thought it should be. Also I don't want the screen to change when the character moves higher on the screen or lower, just left and right public void scrollScreen(){ List<Actor> allObjects = getWorld().getObjects(Actor.class); if(doOnce == 0){ if(this.getX() == 500){ screenCentered = "centered"; doOnce = 1; } } if(screenCentered == "centered"){ if(this.getX() != 500){ for(int i = 0; i < allObjects.size(); i++){ if(this.getX() >= 501){ Actor object = allObjects.get(i); object.setLocation(this.getX() - 1, this.getY()); //this.setLocation(500, this.getY()); }else if (this.getX() <= 499){ Actor object = allObjects.get(i); object.setLocation(this.getX() + 1, this.getY()); //this.setLocation(500, this.getY()); }else{ } } } } }
danpost danpost

2012/12/10

#
An easy way to accomplish side scrolling (or any scrolling) of objects is this: code the actor as you normally would; and put the code for scrolling the objects in the world class, which probably has a reference to the main actor anyway. I am going to call the main actor a 'Hero' class object.
// declared and world instance field assigned its value
Hero mainActor = new Hero();
// in world constructor, you would have
addObject(mainActor, getWidth()/2, 350); // the '350' can be adjusted to suit
// in the act method in the world class, add the following line
scrollObjects();
// add the 'scrollObjects' method to the world class code
private void scrollObjects()
{
    // the following line determines how far off center the main actor is (horizontally)
    int dx = mainActor.getX()-getWidth()/2;
    if(dx==0) return;
    for(Object obj : getObjects(null))
    {
        Actor actor = (Actor) obj;
        actor.setLocation(actor.getX()-dx, actor.getY());
    }
}
UnclePedro UnclePedro

2012/12/10

#
Ah thank you very much! Its working nicely... I think my method had the right idea, but it was a little too complicated... and in the wrong class. Thank you!
You need to login to post a reply.