Sunday, April 17, 2011

2D game in Java API - How to make a scroll game?

This is an extension of the previous post,

"2D game in Java API - Basic format."



A scroll game is a game that has a game map bigger than what is actually displayed.
The user can "scroll" through different parts of the map.

For example, Super Mario is a scroll game because its maps are much bigger than the screen.
As Mario moves right, the whole screen scrolls to the right in order to show hidden parts of the map.

In order to make a scroll game, you have to modify the MainPanel class.

Add the following variables to MainPanel's instance field ::


private int viewX; //x-coordinate of the view.
private int viewY; //y-coordinate of the view.
private final int VIEW_WIDTH; //Width of the view.
private final int VIEW_HEIGHT; //Height of the view.
private final int WORLD_WIDTH; //Width of the world.
private final int WORLD_HEIGHT; //Height of the world.


"WORLD" refers to the entire game map. All the interactions happen in this area.
"VIEW" refers to the area that is displayed on the screen.

If your game map is 1600 pixels long and 900 pixels high, set the WORLD_WIDTH to 1600 and
WORLD_HEIGHT to 900.
If your screen is 600 pixels long and 400 pixels high, set the VIEW_WIDTH to 600 and
VIEW_HEIGHT to 400.
If you want to display the upper-left part of the game map, set viewX and viewY to zero.
And so on.


Adding instance variables is not enough. You have to modify the paintComponent(Graphics g) method
in order to display the scroll effect.

Change the MainPanel class's paintComponent(Graphics g) method like this ::



public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < actorList.size(); i++)
{
//If the game character is inside the view,
if((int)actorList.get(i).getX() > viewX-100
&& (int)actorList.get(i).getX() < viewX+VIEW_WIDTH+100
&& (int)actorList.get(i).getY() > viewY-100
&& (int)actorList.get(i).getY() < viewY+VIEW_HEIGHT+100)
{
//Draw the actor.
g.drawImage(actorList.get(i).getImage(),
(int)actorList.get(i).getX() - viewX,
(int)actorList.get(i).getY() - viewY, null);
}
}
}



When you subtract the upper-left position of the view (viewX,viewY) from the game character's
actual position (getX(),getY()), you get the position of the character to be displayed on the screen.

Try this on your own and see whether it works.



(Appendix)
Accessor / Modifier methods for this additional instance field ::



public int getViewX()
{
return viewX;
}
public void setViewX(int x)
{
viewX = x;
}
public int getViewY()
{
return viewY;
}
public void setViewY(int y)
{
viewY = y;
}
public int getViewWidth()
{
return VIEW_WIDTH;
}
public int getViewHeight()
{
return VIEW_HEIGHT;
}
public int getWorldWidth()
{
return WORLD_WIDTH;
}
public int getWorldHeight()
{
return WORLD_HEIGHT;
}

No comments:

Post a Comment