dofile( "data/scripts/lib/utilities.lua" )

local entity_id = GetUpdatedEntityID()
local pos_x, pos_y, current_rotation = EntityGetTransform( entity_id )

SetRandomSeed(pos_x,pos_y)

local detection_radius = 12

nearby_projectiles = EntityGetInRadiusWithTag( pos_x, pos_y, detection_radius, "projectile")

function rotate_degrees(x, y, degrees)
	return rotate_radians(x, y, math.rad(degrees))
end

function rotate_radians(x, y, radians)
	local ca = math.cos(radians)
	local sa = math.sin(radians)
	local out_x = ca * x - sa * y
	local out_y = sa * x + ca * y
	return out_x, out_y
end

for k, projectile in pairs(nearby_projectiles) do
    if(EntityHasTag(projectile, "projectile_player") == false)then
        local projectile_x, projectile_y = EntityGetTransform( projectile )

        local direction_x = pos_x - projectile_x
        local direction_y = pos_y - projectile_y

        directionX, directionY = rotate_degrees(directionX, directionY, Random(-5,5))

        edit_component( v, "VelocityComponent", function(comp,vars)
            local velocity_x, velocity_y = ComponentGetValueVector2( comp, "mVelocity" )

            local velocity = math.max(velocity_x, velocity_y)

            local vel_x = direction_x
        
            local vel_y = direction_y
            
            local len = math.sqrt((vel_x*vel_x) + (vel_y*vel_y))

            local dir_x = vel_x / len
            local dir_y = vel_y / len

            local force_x = dir_x * velocity
            local force_y = dir_y * velocity
            
            
            ComponentSetValueVector2( comp, "mVelocity", force_x, force_y )

        end)	
    end
end