Getting the closest part of the middle of the screen

I want to get a target from the middle of the camera, but i’m getting very weird magnitudes when I try to get it.
This is what im doing.

	local Target = nil
	local closestmag = math.huge
	local vector = Vector2.new(workspace.CurrentCamera.ViewportSize.X / 2, workspace.CurrentCamera.ViewportSize.Y / 2)
	for i,v in pairs (workspace.Players:GetChildren()) do
		if v:FindFirstChild("HumanoidRootPart") and v ~= Player.Character then
			local mag = (vector - Vector2.new(v.HumanoidRootPart.Position.X, v.HumanoidRootPart.Position.Y)).magnitude; print(mag)
			if mag < 65 and mag < closestmag then
				Target = v; closestmag = mag
			end
		end

When I print the mag, it comes out to be a ridiculous number like 1911. Any solutions?
Target also prints nil.

1 Like

This is not how to map 3D object space to a 2D screen.

There are a couple different ways you should do it. Here are three different methods you can use.

Camera:WorldToViewportPoint()
Camera.CFrame.LookVector
Camera.CFrame:VectorToObjectSpace()

The first you can get any Position in the 3D world and transform it to a point in the camera.

The second one You can simply use the dot product between it and the direction of the target. Biggest result means closest to center.

The third is probably unnecessary. It’s the same as second except working in Object space not world.

3 Likes

Could I get an example of how I would use the first option?

All you have to do is put a position of the object you need in the parameters. Then it returns the position on the screen.

It’s very simple to use.

Basically you can just substitute the code for that.

1 Like

Trying this, but it gives ridiculous magnitudes, like 3000+. This is what I have

	for i,v in pairs (workspace.Players:GetChildren()) do
		if v:FindFirstChild("HumanoidRootPart") and v ~= Player.Character then
			local worldPoint = v.HumanoidRootPart.Position
			local vector, inViewport = camera:WorldToViewportPoint(worldPoint) print(vector, inViewport)
			if inViewport then
			local mag = (vector - v.HumanoidRootPart.Position).magnitude; print(mag)
			if mag < 65 and mag < closestmag then
				Target = v; closestmag = mag
				end
			end
		end
	end
1 Like

It seems like the magnitude changes drastically if i even turn my camera a little bit.

Yes. The distance is counted in pixels.

You should try printing out the Camera’s ViewportSize for reference on how the size would be.

Even better you should have a ratio between the size of the viewport and the mag for example

local Magnitude = Camera.ViewportSize.X / 4 -- Part is 1/2 distance
1 Like