public
Created

2D shadows in LibGDX

  • Download Gist
shadows.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
static Vector2 L = new Vector2();
static Vector2 N = new Vector2();
static Vector2 tmp = new Vector2();
static Vector2[] points = new Vector2[] {
new Vector2(), new Vector2(), new Vector2(), new Vector2()
};
static Vector2[] tmpBoundary = new Vector2[] {
new Vector2(), new Vector2()
};
/**
* For the given light position (x, y with lower-left origin), determine the two
* "shadow boundary" points for the given rectangle (also uses lower-left origin).
* These points are the two that will need to be extended/projected from the light vector,
* in order to construct the shadow geometry. If the light is inside the rectangle, or could
* not find two shadow boundary points, null is returned.
*
* To reduce garbage, this method returns a static array
* with vectors shared across the various shadowBoundary methods.
*
* @param lightPos
* @param rect
* @return
*/
public static Vector2[] shadowBoundary(Vector2 lightPos, Rectangle r) {
//corners, clockwise
points[0].set(r.x, r.y);
points[1].set(r.x + r.width, r.y);
points[2].set(r.x + r.width, r.y + r.height);
points[3].set(r.x, r.y + r.height);
int off = 0;
boolean lastFace = true;
//go through each point + 1
for (int i=0; i<points.length + 1; i++) {
Vector2 p = points[i % points.length];
Vector2 prev = points[i==0 ? points.length-1 : i-1];
//line to point
//light to point vec, normalized
L.set(p).sub(lightPos).nor();
//normalized direction of edge
N.set(p).sub(prev).nor();
//dot product
float dot = N.dot(L);
boolean face = dot < 0;
//skip the first index, we'll come back to it later
if (i!=0) {
if (face != lastFace) {
if (off >= tmpBoundary.length)
return tmpBoundary;
tmpBoundary[off].set(p);
off++;
}
}
lastFace = face;
}
return off==0 ? null : tmpBoundary;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.