--


local function Dash()
	local character = player.Character
	if character and not debounce then
		debounce = true
		-- now we begin the dash script here

		local humanoid = character.Humanoid
		local HRP = character.HumanoidRootPart -- HRP stands for HumanoidRootPart

		local loadedAnimation = humanoid.Animator:LoadAnimation(DashAnimation)

		local dashDirection = nil
		local moveDirection = humanoid.MoveDirection
		local lookVector = HRP.CFrame.LookVector
		local minusVelocity = -velocity -- in CFrame, if we set Z to positive, player will go move backward
		-- instead of forward

		-- checking if player is on ground, not floating
		local isOnGround = humanoid.FloorMaterial ~= Enum.Material.Air and humanoid.FloorMaterial ~= Enum.Material.Water

		if isOnGround then


			if moveDirection == Vector3.new(0,0,0) then -- if player is not currently moving/walking
				dashDirection = HRP.Position + Vector3.new(lookVector.X, 0, lookVector.Z)
			else -- if player are currently moving/walking
				dashDirection = HRP.Position + Vector3.new(moveDirection.X, 0, moveDirection.Z)
			end

			-- using bodygyro to rotate player to the dash direction smoothly
			local bodyGyro = Instance.new("BodyGyro")
			bodyGyro.Parent = HRP
			bodyGyro.MaxTorque = Vector3.new(math.huge, math.huge, math.huge)
			bodyGyro.D = 0 -- D is the dampening
			bodyGyro.P = 500000 -- P is aggressiveness
			bodyGyro.CFrame = CFrame.lookAt(HRP.Position, dashDirection) -- Making player look at the dash direction

			local attachment = Instance.new("Attachment")
			attachment.Parent = HRP

			-- now using VectorForce to move player forward
			local vectorForce = Instance.new("VectorForce")
			vectorForce.Parent = HRP
			-- VectorForce need attachment to tell where is player looking at
			vectorForce.Attachment0 = attachment
			vectorForce.Force = Vector3.new(0,0,minusVelocity) -- now it will move player forward as the settings

			loadedAnimation:Play() -- play the dash animation
			humanoid.AutoRotate = false -- prevent player to rotate by themselves

			wait(duration)

			humanoid.AutoRotate = true

			vectorForce:Destroy()
			bodyGyro:Destroy()
			attachment:Destroy()

			--wait(duration) -- give some time before stopping the dash animation
			loadedAnimation:Stop()

		end


		--
		wait(cooldown)
		debounce = false
	end
end

UserInputService.InputBegan:Connect(function(input)
	if input.KeyCode == key then
		Dash()
	end
end)
