bacongamejam05-notsoalonein.../src/light.coffee

111 lines
3.2 KiB
CoffeeScript

calculate_lightray = (x1, y1, x2, y2, type) ->
switch type
when 'enemy' then selected_layer = enemy_layer
else selected_layer = shadow_layer
pixel_x1 = x1*config.pixelsize + (config.pixelsize/2)
pixel_y1 = y1*config.pixelsize + (config.pixelsize/2)
pixel_x2 = x2*config.pixelsize + (config.pixelsize/2)
pixel_y2 = y2*config.pixelsize + (config.pixelsize/2)
dx = Math.abs(pixel_x1 - pixel_x2)
dy = Math.abs(pixel_y1 - pixel_y2)
s = 0.99 / (if dx>dy then dx else dy)
t = 0.0
# show me the rays
if config.debug
context.beginPath()
context.strokeStyle = 'blue'
context.moveTo(pixel_x1+config.map.origin.x,pixel_y1+config.map.origin.y)
context.lineTo(pixel_x2+config.map.origin.x,pixel_y2+config.map.origin.y)
context.stroke()
hit_wall = false
while t < 1.0
dx = Math.round((1.0-t)*pixel_x1 + t*pixel_x2)
dy = Math.round((1.0-t)*pixel_y1 + t*pixel_y2)
dx = Math.floor(dx/config.pixelsize)
dy = Math.floor(dy/config.pixelsize)
# FLOOR?
if level[dy*config.map.width + dx] is 0
break if hit_wall and !config.debug
if selected_layer[dy*config.map.width + dx] == 0
if t > 0.5
selected_layer[dy*config.map.width + dx] += map_range([0.5, 1], [1, 0], t)
else
selected_layer[dy*config.map.width + dx] += 1
# WALL?
else if level[dy*config.map.width + dx] is 3
break if type is 'enemy'
if t > 0.5
selected_layer[dy*config.map.width + dx] += map_range([0.5, 1], [1, 0], t)
else
selected_layer[dy*config.map.width + dx] += 1
hit_wall = true
# ENTITIY?
else if level[dy*config.map.width + dx] in blocks.entities
if t > 0.5
selected_layer[dy*config.map.width + dx] += map_range([0.5, 1], [1, 0], t)
else
selected_layer[dy*config.map.width + dx] += 1
break if !config.debug and level[dy*config.map.width + dx] isnt 1 and level[dy*config.map.width + dx] isnt 8
else
selected_layer[dy*config.map.width + dx] = .5
break if !config.debug
t += s
illuminate = (x1, y1, range, type = 'shadow') ->
r = 0
while r < Math.PI*2
x2 = range*Math.cos(r) + x1
y2 = range*Math.sin(r) + y1
# bug: edge blurry stuff
#x2 = config.map.width-1 if x2 > config.map.width-1
#y2 = config.map.height-1 if y2 > config.map.height-1
#
#x2 = 0 if x2 < 0
#y2 = 0 if y2 < 0
calculate_lightray(x1, y1, x2, y2, type)
r += 0.03
calculate_lights = () ->
#illuminate(8, 8, 5)
illuminate(toxy(player.position).x, toxy(player.position).y, player.lightrange)
for block, position in level
switch block
# 6 = LIGHT
# CAMERA
when 8
illuminate(toxy(position).x, toxy(position).y, 4, 'enemy')
draw_lights = (type) ->
switch type
when 'enemy'
color = '255, 0, 0'
selected_layer = enemy_layer
else
color = '0, 0, 0'
selected_layer = shadow_layer
for brightness, position in selected_layer
switch type
when 'enemy'
alpha = brightness*.5
else
alpha = 1-brightness
if level[position] in blocks.entities
if alpha < 0.4 then alpha = 0
pixel(position, config.pixelsize, config.pixelsize, 'rgba('+color+', '+alpha+')')