Results 1 to 11 of 11
  1. #1
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    123
    Rep Power
    0

    Default Scrolling backround using swing

    Hi,
    I have been trying to find out how to make a scrolling backroud for a 2D game, but i cant find a good tutorial that explains it well enough.
    If it is not too much trouble, could someone try to explain its principle. And if possible, a simple example program with comments on the lines that matter the most for it to work.

  2. #2
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    123
    Rep Power
    0

    Default Re: Scrolling backround using swing

    anyone?

  3. #3
    jsobel is offline Member
    Join Date
    Apr 2012
    Posts
    68
    Rep Power
    0

    Default Re: Scrolling backround using swing

    Just create a variable named xs representing x scroll, whenever you draw something to the screen excluding the player subtract xs from it. Draw the player in the middle of the screen. Whenever the player moves increments xs by the same amount.

  4. #4
    jsobel is offline Member
    Join Date
    Apr 2012
    Posts
    68
    Rep Power
    0

    Default Re: Scrolling backround using swing

    did it work?

  5. #5
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    123
    Rep Power
    0

    Default Re: Scrolling backround using swing

    You mean it like this: the xs represents my position on the backround. whenever i move the backround moves depending of my movement. And the backround isnt drawn fully on the screen, but the part of where i am.

    Next question is: how can i draw a part of the picture on the screen?

    Sorry for grammar mistakkes and stuff like that, i just came back from a week long camp in the woods and my mind doesent work fully yet.

  6. #6
    jsobel is offline Member
    Join Date
    Apr 2012
    Posts
    68
    Rep Power
    0

    Default Re: Scrolling backround using swing

    Quote Originally Posted by vastrolorde View Post
    You mean it like this: the xs represents my position on the backround. whenever i move the backround moves depending of my movement. And the backround isnt drawn fully on the screen, but the part of where i am.

    Next question is: how can i draw a part of the picture on the screen?

    Sorry for grammar mistakkes and stuff like that, i just came back from a week long camp in the woods and my mind doesent work fully yet.
    what do you mean

  7. #7
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default Re: Scrolling backround using swing

    You could store the background image in a BufferedImage, override paintComponent() on your display component, and use the methods of the Graphics context to copy the appropriate part of the image into the component. If your game is made up of repeating tiles, you could do this many times to draw each screen. Once you get this working, replace the BufferedImage with a VolatileImage. VolatileImages are trickier to use because they can be can be invalidated at any time; you have to check if the image is valid before and after copying from it. But they're potentially hardware accelerated, so many times faster than a software copy from a BufferedImage.
    Get in the habit of using standard Java naming conventions!

  8. #8
    jnaevwa is offline Member
    Join Date
    Jan 2011
    Posts
    7
    Rep Power
    0

    Default Re: Scrolling backround using swing

    Question 1:

    Java Code:
    public class Player
    {
        private int posX, posY, scrollX, scrollY; 
        /*
         * posX is the x position on the screen
         * posY is the y position on the scrren
         * scrollX is the amount to which the background scrolls in the x dimension
         * scrollY is the amount to which the background scrolls in the y dimension
         */
    
        private BufferedImage img, img2; 
        /*
         * img The background of that you want to scroll
         * img2 the character image
         */
        
        public Player()
        {
            //set all the values up, I didn't set the image up in the code I assumed you can do that.
            
            posX = 75;
            posY = 100;
            
            scrollX = 0;
            scrollY = 0;
        }
        
        public void draw(Graphics g)
        {
            Graphics2D g2d = (Graphics2D) g;
            
            /*
             * to draw a scrolling background there is some obvious things we need to do
                 * have a dynamic variable as a coordinate
                 * control it so that it moves slowly and doesn't jump
                 * move from left to right(this is a presumption on my part)
    
            * so lets tackle one at a time 
                 * we set it so that the image is drawn at the scrollX and scrollY values instead of constant x and y values
                 * in the move methods below you will see that we only increase one each time this is so that it gives the impression of moving and not jumping from place to place
                 * again if you look at the move methods below when you move right the backgrounds coordinates get more negative(-) but when you go left it gets more possative
    
            */
            g2d.drawImage(img, scrollX, scrollY, null);
    
            g2d.drawImage(img2,posX,posY,null);
        }
        
        public void moveRight()
        {
            scrollX --;
        }
        
        public void moveLeft()
        {
            scrollX ++;
        }
        
        public void moveUp()
        {
            scrollY ++;
        }
        
        public void moveDown()
        {
            scrollY ++;
        } 
    }
    this is obviously the most bare bones idea but just to try and clear things up if they where not.

    Question 2:

    well if I understand you right the best way I think is to use java.awt.Graphics method
    drawImage

    public abstract boolean drawImage(Image img,
    int dx1,
    int dy1,
    int dx2,
    int dy2,
    int sx1,
    int sy1,
    int sx2,
    int sy2,
    ImageObserver observer)

    Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface. Transparent pixels do not affect whatever pixels are already there.
    This method returns immediately in all cases, even if the image area to be drawn has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete then drawImage returns false. As more of the image becomes available, the process that draws the image notifies the specified image observer.

    This method always uses the unscaled version of the image to render the scaled rectangle and performs the required scaling on the fly. It does not use a cached, scaled version of the image for this operation. Scaling of the image from source to destination is performed such that the first coordinate of the source rectangle is mapped to the first coordinate of the destination rectangle, and the second source coordinate is mapped to the second destination coordinate. The subimage is scaled and flipped as needed to preserve those mappings.

    Parameters:
    img - the specified image to be drawn
    dx1 - the x coordinate of the first corner of the destination rectangle.
    dy1 - the y coordinate of the first corner of the destination rectangle.
    dx2 - the x coordinate of the second corner of the destination rectangle.
    dy2 - the y coordinate of the second corner of the destination rectangle.
    sx1 - the x coordinate of the first corner of the source rectangle.
    sy1 - the y coordinate of the first corner of the source rectangle.
    sx2 - the x coordinate of the second corner of the source rectangle.
    sy2 - the y coordinate of the second corner of the source rectangle.
    observer - object to be notified as more of the image is scaled and converted.

    Returns:
    true if the current output representation is complete; false otherwise.

    Since:
    JDK1.1

    See Also:
    Image, ImageObserver, ImageObserver.imageUpdate(java.awt.Image, int, int, int, int, int)
    however If your talking about tiling then there is a decently easy way using the code I already provided and modulus(%) and bit of math.

  9. #9
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    123
    Rep Power
    0

    Default Re: Scrolling backround using swing

    got it working. Double draw the backround image, only the second one with some X axsis delay.

    I dont know if its picture related or code related, but is there a way to make my program recognize colors. So if i have a black color on picture then it turns it invisivble or something like that?
    Last edited by vastrolorde; 04-06-2013 at 05:14 PM.

  10. #10
    jnaevwa is offline Member
    Join Date
    Jan 2011
    Posts
    7
    Rep Power
    0

    Default Re: Scrolling backround using swing

    to do this have to modify the code in several places. So lets start at the top

    first we need to create a few new variable (I call them x,y,screenWidth,screenHeight,scrollX2)
    Java Code:
        private int x,y,posX, posY, scrollX, scrollX2, scrollY, screenWidth, screenHeight;
    next we will need to set these variable up with a value (I personal recommend that you put the screen dimensions as the parameters but thats just me)
    Java Code:
        public Player(int screenWidth, int screenHeight)
        {
            //set all the values up, I didn't set the image up in the code I assumed you can do that.
            
            x = 0;
            y = 0;
             
            posX = 75;
            posY = 100;
             
            scrollX = 0;
            scrollX2 = screenHeight; //you will see why we set this to screen height in a bit
            scrollY = 0;
            
            this.screenWidth = screenWidth;
            this.screenHeight = screenHeight;
        }
    okay now that we have are variables and have initialized them we go on to the draw method
    Java Code:
        public void draw(Graphics g)
        {
            Graphics2D g2d = (Graphics2D) g;
            
            double point = img.getWidth()/((double)screenWidth);
            int point2 = (int)point;
            double pointDiff = point - point2;
            double actPoint = pointDiff * screemWidth;
            
            if ((this.getX() - (actPoint-1)) % (img.getWidth()*2) == 0)
            {
                scrollX = 0;
            }
            if ((this.getX() - (img.getWidth() + (actPoint-1))) % (img.getWidth()*2) == 0)
            {
                scrollX2 = 0;
            }
            
            g2d.drawImage(img, screenWidth - scrollX2, scrollY, null);
            if (this.getX() > actPoint-1)
            {
                g2d.drawImage(img, screenWidth - scrollX, scrollY, null);
            }
            
    
            g2d.drawImage(this.getImage(),posX,posY,null);
        }
    it looks complicated until you brake it into pieces. this first peice calculates where on the screen the background will end that getting where we draw the next one
    Java Code:
            double point = img.getWidth()/((double)screenWidth);
            int point2 = (int)point;
            double pointDiff = point - point2;
            double actPoint = pointDiff * screenWidth;
    I won't go into exactly how(mostly because without drawing it out its hard to explain)

    the next new peice is
    Java Code:
             if ((this.getX() - (actPoint-1)) % (img.getWidth()*2) == 0)
            {
                scrollX = 0;
            }
            if ((this.getX() - (img.getWidth() + (actPoint-1))) % (img.getWidth()*2) == 0)
            {
                scrollX2 = 0;
            }
    this works based on your players x coordinate and the point to which the background changes divided by the scrolling images width taken twice and that remainder. if this still don't make complete sense of this(because I honestly don't really know how to explain this any better) I suggest you take it plug some numbers in and it might make some more sense. just remember that actPoint is where the next background will begin

    the next piece is pretty straightforward
    Java Code:
            g2d.drawImage(img, screenWidth - scrollX2, scrollY, null);
            if (this.getX() > actPoint-1)
            {
                g2d.drawImage(img, screenWidth - scrollX, scrollY, null);
            }
    essentially it just draws the images where the variables say to the if statement just determines which variable etc...

    thats all the new peices to the draw method now we have to change the move method slightly
    Java Code:
    public void moveRight()
        {
            x++;
            scrollX ++;
            scrollX2 ++;
        }
         
        public void moveLeft()
        {
            x--;
            scrollX --;
            scrollX2 --;
        }
         
        public void moveUp()
        {
            y--;
            scrollY --;
        }
         
        public void moveDown()
        {
            y++;
            scrollY ++;
        }
    pretty straight forward I think, just incrementing the variables

    And we are done simply tiling with this class. I hope that answers you question as for the secode "codelike thing" that was me quoting the javadocs after misunderstanding what you where looking for.

    Hopes this helps




    EDIT:
    Sorry about the double post earlier my computer was being really derpy :(

    as to your question about colours I personal don't have a clue but I found this

    public static void main(String[] args) throws Exception {

    File in = new File("C:\\Users\\Christoffer\\Desktop\\christoffer .jpg");
    BufferedImage source = ImageIO.read(in);

    int color = source.getRGB(0, 0);

    Image image = makeColorTransparent(source, new Color(color));

    BufferedImage transparent = imageToBufferedImage(image);

    File out = new File("C:\\Users\\Christoffer\\Desktop\\trans.PNG") ;
    ImageIO.write(transparent, "PNG", out);

    }

    private static BufferedImage imageToBufferedImage(Image image) {

    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = bufferedImage.createGraphics();
    g2.drawImage(image, 0, 0, null);
    g2.dispose();

    return bufferedImage;

    }

    public static Image makeColorTransparent(BufferedImage im, final Color color) {
    ImageFilter filter = new RGBImageFilter() {

    // the color we are looking for... Alpha bits are set to opaque
    public int markerRGB = color.getRGB() | 0xFF000000;

    public final int filterRGB(int x, int y, int rgb) {
    if ((rgb | 0xFF000000) == markerRGB) {
    // Mark the alpha bits as zero - transparent
    return 0x00FFFFFF & rgb;
    } else {
    // nothing to do
    return rgb;
    }
    }
    };

    ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
    return Toolkit.getDefaultToolkit().createImage(ip);
    }
    http://stackoverflow.com/questions/6...nd-save-as-png

    hope this helps (again)
    Last edited by jnaevwa; 04-07-2013 at 05:08 PM.

  11. #11
    vastrolorde is offline Senior Member
    Join Date
    Jan 2013
    Posts
    123
    Rep Power
    0

    Default Re: Scrolling backround using swing

    Bout that scrolling backound to make it infinite scroll. I madeit so: it draws 2 backround at once. (cordinates on X axis only) 0 - 400 is the first image and 400-800 is the second image. When the variable sxrollX raches 400 it will be zeroed out and loop start at the beginning.

Similar Threads

  1. Side Scrolling
    By djokovic in forum Java 2D
    Replies: 2
    Last Post: 08-01-2012, 09:37 PM
  2. Side-scrolling
    By shadycharacter in forum New To Java
    Replies: 0
    Last Post: 04-21-2010, 04:20 PM
  3. picture backround
    By safiya in forum NetBeans
    Replies: 1
    Last Post: 10-18-2008, 07:13 AM
  4. Scrolling with JTables
    By hiranya in forum AWT / Swing
    Replies: 5
    Last Post: 10-30-2007, 08:48 AM
  5. JScrollPane not scrolling
    By Riftwalker in forum Advanced Java
    Replies: 2
    Last Post: 07-17-2007, 08:16 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •