Problem with Magnitude and Player:DistanceFromCharacter

I am making a turn-based battle system. I am stumped on one part, getting the distance.
It seems pretty simple

 (FirstVector- SecondVector).Magnitude

Since I am working with players, I can simply use a handy method:

Player:DistanceFromCharacter(SecondVector)

(I have been debugging my code)
However, when I am very far from the SecondVector (say 30 studs), it prints 0 (as well as the first method)! Whenever I get very close (say 5 studs), it prints 29. It rarely works.

Here is my code:

local function DetectNearestPlayer(Model, RequiredDistance)
       local Players = game:GetService("Players")
	    for _, Player in pairs(Players:GetPlayers()) do		
		    assert(RequiredDistance, "Invalid Argument to DetectNearestPlayer: no RequiredDistance")
				
		    local Point = self.Model.HumanoidRootPart
		    local Distance = Player:DistanceFromCharacter(Point.Position)		
		    if Distance <= RequiredDistance then
			     return Player
		    end
	  end
end

The only solution I attempted: subtracting vectors and getting the difference’s magnitude (failed)

I could try raycasting or Regoin3’s, but I am unfamiliar with both of those and their API’s.

Thank you in advance

It is possible that you are receiving 0 because a Player does not have a Character. From the DevHub:

Returns the distance between the character’s head and the given Vector3 point. Returns 0 if the player has no character.

I suggest you check if each Player has a Character before calling :DistanceFromCharacter().

As for why the function sometimes returns 29, it is possibly because your function doesn’t work the way the name would suggest. Currently, it returns the first player it finds less than the RequiredDistance away. What you want to do instead is keep a running variable of which Player is closest and how far they are. If the for loop then comes across a Player that is closer, update the variable. Then, only after the for loop finishes should you return the closest Player (or nil if no Players are within the RequiredDistance).

4 Likes