--------------------------------------------------------------------------------------------------------------------------
----------------------------------------------GRENADES---------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------



VELOCITY = 90

function firenade(mouse_pos)
	nadeloaded=false
	local head=game.Workspace:findFirstChild(script.Parent.Parent.Name).Head
	if head == nil then return end
	
	local dir = mouse_pos - head.Position
	dir = computeDirection(dir)

	local launch = head.Position + 5 * dir

	local delta = mouse_pos - launch
	
	local dy = delta.y
	
	local new_delta = Vector3.new(delta.x, 0, delta.z)
	delta = new_delta

	local dx = delta.magnitude
	local unit_delta = delta.unit

	local g = (-9.81 * 20)

	local theta = computeLaunchAngle(dx, dy, g)

	local vy = math.sin(theta)
	local xz = math.cos(theta)
	local vx = unit_delta.x * xz
	local vz = unit_delta.z * xz

	local missile = Instance.new("Part")
	missile.Size = Vector3.new(1,1,1)
	missile.BrickColor=BrickColor.new(0)
	missile.Shape = 0
	missile.BottomSurface = 0
	missile.TopSurface = 0
	missile.Name = "Grenade"
	missile.Elasticity = .2
	missile.Reflectance = 0
	missile.Friction = .8        
	missile.Position = launch
	missile.Velocity = Vector3.new(vx,vy,vz) * VELOCITY

	script.Parent.GrenadeScript:clone().Parent=missile
	missile.GrenadeScript.Disabled = false

	local creator_tag = Instance.new("ObjectValue")
	creator_tag.Value = game.Players.LocalPlayer
	creator_tag.Name = "creator"
	creator_tag.Parent = missile
	
	missile.Parent = game.Workspace

	wait(0.5)
	script.Parent.mode.Value=script.Parent.mode.Value-10
	wait(10)
	nadeloaded=true

end

function computeLaunchAngle(dx,dy,grav)
	local g = math.abs(grav)
	local inRoot = (VELOCITY^4) - (g * ((g*dx*dx) + (2*dy*(VELOCITY^2))))
	if inRoot <= 0 then
		return .25 * math.pi
	end
	local root = math.sqrt(inRoot)
	local inATan1 = ((VELOCITY^2) + root) / (g*dx)

	local inATan2 = ((VELOCITY^2) - root) / (g*dx)
	local answer1 = math.atan(inATan1)
	local answer2 = math.atan(inATan2)
	if answer1 < answer2 then return answer1 end
	return answer2
end

function computeDirection(vec)
	local lenSquared = vec.magnitude * vec.magnitude
	local invSqrt = 1 / math.sqrt(lenSquared)
	return Vector3.new(vec.x * invSqrt, vec.y * invSqrt, vec.z * invSqrt)
end

