dofile_once( "data/scripts/lib/utilities.lua" )
dofile( "mods/spellbound_bundle/files/scripts/utils.lua" )
local entity_id    = GetUpdatedEntityID()
local pos_x, pos_y = EntityGetTransform( entity_id )
local max_dir_ratio_change = 1

edit_component( entity_id, "VelocityComponent", function(comp,vars)
	local vel_x,vel_y = ComponentGetValueVector2( comp, "mVelocity")
	local vel = get_magnitude(vel_x,vel_y)
	if vel <= 900 then
		if vel <= 30 then
			vel = 30
		end
		vel = vel * 1.3
	end
	local ratio = max_dir_ratio_change * (math.min(vel,600)/600)

	local x = EntityGetVariable(entity_id, "target_x", "int") or pos_x
	local y = EntityGetVariable(entity_id, "target_y", "int") or pos_y

	local target = EntityGetVariable(entity_id, "target", "int")
	if(target ~= nil)then
		if(EntityGetIsAlive(target))then
			x, y = EntityGetTransform(target)
		end
	end

	if get_distance(x, y, pos_x, pos_y) <= 10 then
		--newdir = dir
		local projectile_component = EntityGetFirstComponentIncludingDisabled( entity_id, "ProjectileComponent" )
		-- set lifetime to 1
		ComponentSetValue2( projectile_component, "lifetime", 1)
		return
	end

	local dir = get_direction(  x,y,pos_x, pos_y )
	local dir2 = 0 - math.atan2( vel_y, vel_x )
	local delta = math.atan2( math.sin( dir - dir2 ), math.cos( dir - dir2 ) )
	if math.abs(delta) >= math.pi/2 then
		delta = (math.pi/2) * (delta/math.abs(delta))
	end
	local newdir = dir2 + delta * ratio
	local addx = math.cos( newdir ) * vel
	local addy = 0 - math.sin( newdir ) * vel
	vel_x = addx
	vel_y = addy
	ComponentSetValueVector2( comp, "mVelocity", vel_x, vel_y)


end)