Help with swimming outside of terrain water

I’ve been trying to recreate the terrain water swimming mechanics using water parts, using Aorda’s code (How to create terrain water behavior, without terrain water - #13 by Aorda) and modifying it slightly.

I got most of it down apart from the fact that the player will float until the HumanoidRootPart no longer touches the water, where the player will stay stationary. The problem is how unnatural this looks; I’d rather have the water be around the character’s shoulder level

(Aorda’s original code didn’t have this issue but it made the character shake when at the surface)

Here’s my code right now…

local Workspace = game:GetService("Workspace")

local waterPart = {}

for i, part in pairs(Workspace:GetDescendants()) do
	if part.Name == "Water" and part:IsA("BasePart") then
		table.insert(waterPart, part)
	end
end

local RunService = game:GetService("RunService")
local char = script.Parent
local hum = char:WaitForChild("Humanoid")
local hrp = char:WaitForChild("HumanoidRootPart")
local swim

RunService.Heartbeat:Connect(function()
	for i=1, #waterPart do
		local isSwimming
		local isFloating = false
		waterPart[i].Touched:Connect(function() end)
		
		local touching = waterPart[i]:GetTouchingParts()
		for i=1, #touching do
			for _, part in pairs(char:GetDescendants()) do
				if part:IsA("BasePart") and touching[i] == part then
					isFloating = true
				else
				end
			end
			if touching[i] == hrp then
				isSwimming = true
				break
			end
			isSwimming = false
		end
		
		if isSwimming == true then
			if not swim then
				swim = Instance.new("BodyVelocity")
				swim.Parent = hrp
			end
			swim.Velocity = hum.MoveDirection * hum.WalkSpeed + Vector3.new(0,4,0)
			if hum:GetState() ~= Enum.HumanoidStateType.Swimming then
				hum:SetStateEnabled(Enum.HumanoidStateType.GettingUp, false)
				hum:ChangeState(Enum.HumanoidStateType.Swimming)
			end
		elseif swim and isSwimming == false and isFloating == true then
			swim.Velocity = hum.MoveDirection * hum.WalkSpeed + Vector3.new(0,0,0)
		elseif swim and isSwimming == true then
			swim.Velocity = hum.MoveDirection * hum.WalkSpeed
		elseif swim and isFloating == false then
			swim:Destroy()
			swim = nil
			hum:SetStateEnabled(Enum.HumanoidStateType.GettingUp, true)
		end
	end
end)

Thanks for the help!

4 Likes

What you can do is make the part that makes you swim invisible and make it shorter, then add a new part that represents the water.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.