I am currently trying to implement simple lighting into my game. My world is represented in a 2d array of numbers, each number being a certain tile. I am changing the color parameter in the spritebatch.Draw method to dim the tiles, and that is working quite well for me(I don't know how to use shaders).Each tile can have a light level from 0 to 5, and depending on its level it will be brighter/darker. The problem I have is that I used this code to simulate lighting:
public void Update()
{
foreach (NonCollisionTiles tile in nonCollisionTiles)
{
foreach (NonCollisionTiles otherTile in nonCollisionTiles)
{
if (otherTile.Rectangle.X == tile.Rectangle.X && (otherTile.Rectangle.Y / size == tile.Rectangle.Y - 1 || otherTile.Rectangle.Y / size == tile.Rectangle.Y + 1))
{
if (tile.Light < otherTile.Light)
{
tile.Light = otherTile.Light - 1;
}
}
else if (otherTile.Rectangle.X / size == tile.Rectangle.Y && (otherTile.Rectangle.X / size == tile.Rectangle.X - 1 || otherTile.Rectangle.Y / size == tile.Rectangle.X + 1))
{
if (tile.Light < otherTile.Light)
{
tile.Light = otherTile.Light - 1;
}
}
}
}
}
But I'm not sure if it works or not and it lowers my FPS to 1. I have no idea as to how I can implement my lighting system. Essentially, I want it to look like a torch in Minecraft, but in 2d. Here is the code for my tiles:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
namespace Tile_Map
{
class Tiles
{
protected Texture2D texture;
protected int light = 1;
public int Light
{
get { return light; }
set
{
light = value;
}
}
protected Color color;
private Rectangle rectangle;
public Rectangle Rectangle
{
get { return rectangle; }
protected set { rectangle = value; }
}
private static ContentManager content;
public static ContentManager Content
{
protected get { return content; }
set { content = value; }
}
public void Update()
{
color = new Color(light*51,light*51,light*51);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, rectangle, null, color, 0, Vector2.Zero,SpriteEffects.None,0f);
}
}
class CollisionTiles : Tiles
{
public CollisionTiles(int i, Rectangle newRectangle)
{
texture = Content.Load<Texture2D>(@"Images\Tile" + i);
this.Rectangle = newRectangle;
}
}
class NonCollisionTiles : Tiles
{
public NonCollisionTiles(int i, Rectangle newRectangle)
{
texture = Content.Load<Texture2D>(@"Images\Tile" + i);
this.Rectangle = newRectangle;
}
}
}
This is what I am trying to do:
Any help is appreciated!