I have made an egg hatching system that needs to determine the nearest player to the egg so it can work. However, it only either prints the name of only 1 of the eggs or just prints “Cannot hatch”. Please help, I’m open to any suggestions!
Script:
uis.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.E then
if canHatch == true and player.Character ~= nil then
local nearestEgg
local plrPos = player.Character.HumanoidRootPart.Position
for i, v in pairs(Eggs:GetChildren()) do
if nearestEgg == nil then
nearestEgg = v
else
if (plrPos - v.PrimaryPart.Position).Magnitude < (v.PrimaryPart.Position - plrPos).Magnitude then
nearestEgg = v
end
end
end
print(nearestEgg)
else
print("Cannot hatch")
end
end
end)
Use the debugger to step through the code and see the different variables step by step. You should discover that some variables don’t have the values you expected, indicating where the bug might be. It’s easy to guess though, because the only way “Cannot hatch” can print is if canHatch == true and player.Character ~= nil fails. Since the character probably exists, you must be setting canHatch wrong somewhere else.
you’re compaing one thing to itself. (a - b).Magnitude always equals (b - a).Magnitude. You should compare the distance from v to the player to the distance from the nearestEgg to the player.
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Folder = workspace:WaitForChild("Folder")
local function FindChildClosestToPlayer()
local ClosestChild, ClosestDistance = nil, math.huge
for _, Child in ipairs(Folder:GetChildren()) do
local Distance = Player:DistanceFromCharacter(Child.Position)
if Distance < ClosestDistance then
ClosestChild = Child
ClosestDistance = Distance
end
end
if ClosestChild then
return ClosestChild, ClosestDistance
end
end
local Child, Distance = FindChildClosestToPlayer()
Here’s an example script of how you’d go about finding the closest instance of a folder of instances to a player’s character.
local function findNearestEnemy()
getTargets()
for i,v in pairs(targets:GetChildren()) do
local distance = (script.Parent.hemalurgicSpike.Position - v.Position).magnitude
if previousDistance > distance then
target = v
previousDistance = distance
target.Name = "TARGET"
end
end
end
For some reason, both the target’s names are TARGET