Search code examples
javagame-physics

Making it day/night in a java game(light/dark)


I'm currently building a game in java for fun and educational purposes. It is a 2d tilebased game. The rendering is done pixel by pixel through rgb values. I do not use any libraries/game engines currently.

I have however run into problem that lies beyond my basic knowledge of java programming. I intend to add a day/night cycle but realised that I had no idea how to add lighting in to a game. I am thinking that tweaking the rgb values might be an option, but i do not know if that is viable or how it would be done.

So, is it possible to add lighting/darkness to the game without an engine or use of libraries (if so, then how would this be done)?


Solution

  • Take a look at RGB color model: http://en.wikipedia.org/wiki/RGB_color_model

    In summary, you have three color channels (Red, Green, Blue) and the higher each color channel value the brigther the color is.

    So you can create a darker color by separating the color channels, reducing their values by some amount and recombine the channels to RGB:

    public static int muchDarker(int rgb) {
        int r = (rgb >> 16) & 255;   // red
        int g = (rgb >> 8) & 255;    // green
        int b = rgb & 255;           // blue
        // now reduce brightness of all channels to 1/3
        r /= 3;
        g /= 3;
        b /= 3;
        // recombine channels and return
        return (r << 16) | (g << 8) | b;
    }