local U = require "scriptbank\\utillib" local lights = {} attachLightToMe = attachLightToMe or {} local rad = math.rad function light_npc_init( e ) lights[ e ] = { lightNum = GetEntityLightNumber( e ), attachTo = nil } end local function sqrd( x1, z1, x2, z2 ) local dx, dz = x1 - x2, z1 - z2 return dx * dx + dz * dz end function light_npc_main( e ) local light = lights[ e ] if light == nil then return end if light.attachTo == nil then local x1, y1, z1 = GetLightPosition( light.lightNum ) local dist1 = math.huge local closest = nil for _, v in pairs( attachLightToMe ) do if v ~= nil then local x2, y2, z2 = GetEntityPosAng( v ) local dist2 = sqrd( x1, z1, x2, z2 ) if dist2 < dist1 then closest = v dist1 = dist2 end end end if closest == nil then light.attachTo = -1 return end attachLightToMe[ closest ] = nil light.attachTo = closest --get the entity pos & angles values we are attaching too local x, y, z, Ax, Ay, Az = GetEntityPosAng( closest ) --get our own (light) values local lx, ly, lz, lax, lay, laz = GetEntityPosAng( e ) --work out the offsets (done once at map start) light.offx = lx - x light.offy = ly - y light.offz = lz - z --store the angle offset as a radian for vector use for later light.offax = rad( lax - Ax ) light.offay = rad( lay - Ay ) light.offaz = rad( laz - Az ) elseif light.attachTo ~= -1 then --this part is run during the update --get the new values for our attached entity local x, y, z, Ax, Ay, Az = GetEntityPosAng( light.attachTo ) --place the light based on the new position + our offset local xA, yA, zA = rad( Ax ), rad( Ay ), rad( Az ) local xo, yo, zo = U.Rotate3D( light.offx, light.offy, light.offz, xA, yA, zA ) SetLightPosition ( light.lightNum, x + xo, y + yo, z + zo ) --work out the angle of the entity + our angle offset local xv, yv, zv = U.Rotate3D( 0, 0, 1, xA + light.offax, yA + light.offay, zA + light.offaz ) SetLightAngle( light.lightNum, xv, yv, zv ) end end