Guest User

Untitled

a guest
Oct 17th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. /**
  2. * Get the effect the light should apply to a given location
  3. *
  4. * @param map The tile map you're lighting (I'm assuming you've got something)
  5. * @param x The x coordinate of the location being considered for lighting
  6. * @param y The y coordinate of the location being considered for lighting
  7. * @param colouredLights True if we're supporting coloured lights
  8. *
  9. * @return The effect on a given location of the light in terms of colour components (all
  10. * the same if we don't support coloured lights)
  11. */
  12. public float[] getEffectAt(Map map, float x, float y, boolean colouredLights) {
  13. // first work out what propotion of the strength distance the light
  14. // is from the point. This is a value from 0-1 where 1 is the centre of the
  15. // light (i.e. full brightness) and 0 is the very edge (or outside) the lights
  16. // range
  17. float dx = (x - xpos);
  18. float dy = (y - ypos);
  19.  
  20. // first work out how many steps along the line we're going to do
  21. // should really work out the distance here, but a Math.sqrt() is probably pretty expensive
  22. int steps = (int) ((Math.abs(dx) + Math.abs(dy)) * 4);
  23.  
  24. // now work out how far on each move we want to go (using minus dx/dy here since the previous calculations worked it out
  25. // in the wrong direction)
  26. float stepX = (-dx / steps);
  27. float stepY = (-dy / steps);
  28.  
  29. // start at the position of the light
  30. float px = x;
  31. float py = y;
  32.  
  33. // move across the map checking the points
  34. for (int i=0;i<steps-1;i++) {
  35. if (map.blocked((int) px, (int) py)) {
  36. return 0;
  37. }
  38.  
  39. // move to the next point
  40. px += stepX;
  41. py += stepY;
  42. }
  43.  
  44. // once we reach this point we know the light isn't blocked
  45.  
  46. // calculate the brightness
  47. float distance2 = (dx*dx)+(dy*dy);
  48. float effect = 1 - (distance2 / (strength*strength));
  49.  
  50. if (effect < 0) {
  51. effect = 0;
  52. }
  53.  
  54. // if we doing coloured lights then multiple the colour of the light
  55. // by the effect. Otherwise just use the effect for all components to
  56. // give white light
  57. if (colouredLights) {
  58. return new float[] {col.r * effect, col.g * effect, col.b * effect};
  59. } else {
  60. return new float[] {effect,effect,effect};
  61. }
  62. }
Add Comment
Please, Sign In to add comment