2D lights and shadow system for games or other.

edited October 2017 in Share Your Work

Thanks jeremydouglass ! :)

PImage bg;
PImage light, screen;
PGraphics lightMask;
PGraphics pg;
boolean lights;
int x;
void setup() {
  size(480, 270);
  frameRate(60);
  bg = loadImage("https://ichef.bbci.co.uk/images/ic/480xn/p01lckx1.jpg");
  bg.resize(width, height);
  light = bg.copy();
  lightMask = createGraphics(width, height);
}
void draw() {
  background(199);
  image(bg, 0, 0);
  screen = get(0, 0, width, height);

  fill(0, 250);
  noStroke();
  rect(0, 0, width, height);
  pg = lightMask;
  pg.beginDraw();
  pg.background(0, 0);
  pg.blendMode(ADD);
  pg.noStroke();
  drawLight(x, height/2, x/2);
  x+=3;
  if (x>=width) {
    x=0;
  }
  pg.endDraw();
  screen.mask(lightMask);
  image(screen, 0, 0);
  fill(255, 255, 0);
  textAlign(LEFT, TOP);
  textSize(39);
  text(int(frameRate) + " FPS", 5, 5);
  textAlign(LEFT, BOTTOM);
  textSize(10);
  fill(255);
  text("Press key \"L\" to lights rendering smooth or fast.",5,height-5);
}
void drawLight(int x, int y, float radius) {
  for (int i=0; i<=radius/2; i++) {
    //pg.fill(0+i*255/radius*2);
    pg.fill(1);
    if (!lights) {
      pg.fill(50);
      radius = radius/1.2;
    }
    pg.ellipse(x, y, radius-i*2, radius-i*2);
    if (!lights) {
      i=int(radius/2);
    }
  }
}
void keyPressed() {
  if (key == 'l' || key == 'L') {
    if (lights) {
      lights = false;
    } else {
      lights = true;
    }
  }
}

Comments

Sign In or Register to comment.