The Shadow Realm

While working on one of the games, I wrote some code that makes shadows super easy. So today I'm sharing that code.

Quick Month of Games update: one of the games is done. It's uploaded and has been approved by Google, so let's hope I remember to hit publish.

I wanted to add some basic shadows to objects, but didn't have a lighting system. My first thought was use an image editor to create darker copies of the objects that I wanted shadows for. But I was too lazy to do that, so wondered if I could do it in code. And it turns out I could.

// Extension method to create a copy of texture which converts all coloured pixels into shadows
public static Texture2D CreateShadowTexture(this Texture2D source)
{
      // Create a new texture using the original's GraphicsDevice, width and height
      Texture2D texture = new Texture2D(source.GraphicsDevice, source.Width, source.Height);

      // Create an array of colours, using the amount of pixels in the original texture to determine the array size (amount of pixels = width * height)
      Color[] data = new Color[source.Width * source.Height];

      // Copy the colour data from the original texture into the new texture
      source.GetData(0, source.Bounds, data, 0, source.Width * source.Height);

      // Loop through each pixel in the texture
      for (int i=0; i<data.Length; i++)
      {
            // If the current pixel's alpha is not 0 (not transparent)
            if (data[i].A != 0)
            {
                // Set the red, green and blue values to 0 (r0g0b0 = black)
                data[i].R = 0;
                data[i].G = 0;
                data[i].B = 0;

                // Set the alpha to 150 to make it semi transparent
                data[i].A = 150;
            }
      }

      // Set the colour data onto the new texture
      texture.SetData(data);

      // Copy the name of the texture over
      texture.Name = source.Name;

      // Return the new texture
      return texture;
}

The code above is an extension method, so it could be used like:

Texture2D originalTexture = Content.Load<Texture2D>("objects");

Texture2D shadows = originalTexture.CreateShadowTexture();

spriteBatch.Draw(originalTexture, Vector2.Zero, Color.White);

spriteBatch.Draw(shadows, Vector2.One, Color.White);

The way I have set it up in my project is I have a Shadow class which copies the texture in the constructor. It then has some properties to keep track of the position and the rotation, and some methods to set them. Whenever the object moves, it then calls the methods on the shadow to update them too.

There, I did it! Some actual game dev.

Popular posts from this blog

Getting Started with the FireRed Decompilation

Phoning It In

Tonight Matthew, I'm Going to Make...