How to detect negative Y magnitude

I wanna make it so the altitude stays at 0 if the player goes too far down. But if seems to still track the distance instead of going negative.

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local plr = Players.LocalPlayer
local chr = plr.Character
local hroot = chr:WaitForChild("HumanoidRootPart")

local SpawnPoint = workspace.SpawnLocation
local Label = script.Parent

RunService.Heartbeat:Connect(function()
	local spawnpos = Vector3.new(0,SpawnPoint.Position.Y,0)
	local hrootpos = Vector3.new(0,hroot.Position.Y,0)
	local distance = (spawnpos - hrootpos).Magnitude

	Label.Text = math.floor(distance)
end)
1 Like

To explain what I did here, math.max will return the smallest value given to it, so, when the altitude goes below zero, it will return zero, and, since you only need the Y coordinate, there is no need for the Vector3’s, just the Y-coordinate as a number is enough

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local plr = Players.LocalPlayer
local chr = plr.Character
local hroot = chr:WaitForChild("HumanoidRootPart")

local SpawnPoint = workspace.SpawnLocation
local Label = script.Parent

RunService.Heartbeat:Connect(function()
	local spawnpos = SpawnPoint.Position.Y
	local hrootpos = hroot.Position.Y
	local distance = math.max((hroot.Position.Y - SpawnPoint.Position.Y),0)

	Label.Text = math.floor(distance)
end)
2 Likes

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