How to detect if the mouse is clicking a part inside a worldmodel(on a viewportframe)

I’m trying to detect mouse clicks on Parts/Models inside a WorldModel that’s rendered in a fullscreen ViewportFrame. The goal is simply to know which model the player clicked.

The problem is that the click is not being detected at all on the objects inside the WorldModel. Since this is a ViewportFrame, Mouse.Target doesn’t work, and the raycast I’m using isn’t hitting anything.

This is the script I tried:

local function GetClickedModel(part)
	while part and not part:IsA("Model") do
		part = part.Parent
	end
	return part
end

local function DetectCardClick(input)
	if input.UserInputType ~= Enum.UserInputType.MouseButton1 then return end

	local mousePos = UserInputService:GetMouseLocation()
	local framePos = ViewPortFrame.AbsolutePosition
	local frameSize = ViewPortFrame.AbsoluteSize

	local relX = mousePos.X - framePos.X
	local relY = mousePos.Y - framePos.Y

	if relX < 0 or relY < 0 or relX > frameSize.X or relY > frameSize.Y then
		return
	end

	local ray = ViewPortCam:ViewportPointToRay(relX, relY)

	local params = RaycastParams.new()
	params.FilterType = Enum.RaycastFilterType.Whitelist
	params.FilterDescendantsInstances = { ViewPortFrame.WorldModel }
	params.IgnoreWater = true

	local result = workspace:Raycast(
		ray.Origin,
		ray.Direction * 1000,
		params
	)

	if result then
		local model = GetClickedModel(result.Instance)
		if model then
			print("Model clicked:", model.Name)
		end
	end
end

The ViewportFrame is fullscreen, has its own Camera, and all clickable objects are inside a WorldModel.

Hi! Honestly, I want to say that I am blown away by the cool animation in the video lol! Really creative idea :smiley:

Anyways, I will point out the key issue in your code which is point out in Camera Documentation and a potential solution.

The problem

If you read the documentation I linked up there, you will notice a note that say


what this means is that :ViewportPointToRay() unfortunatly cannot be used directly for viewportFrames. This is because the viewport size is incorrect leading to it calculating invalid ray direction.

The solution

Since roblox does not support this function in viewportFrames, we will BECOME the roblox engineers and write our own function to do something like that. I will not provide you will the entire code in the sense of the entire code(i mean that you cannot just copy and paste in one click) but I wll provide sniplets for you to to copy and paste multiple times. This is to make you hopefully read my explanation :face_holding_back_tears:

defining the function and paramters

Firstly, we will need to define the function (obviously). For this function, we will need parameters such as ViewportFrame, realtive mouse X and relative mouse Y

--[[
@param viewport: ViewportFrame
@param x: mouse X position relative to viewport AbsolutePosition.X (mouse - viewportPos)
@param y: mouse Y position relative to viewport AbsolutePosition.Y (mouse - viewportPos)
]]
local function ViewportPointToRay(viewport:ViewportFrame,x:number,y:number)
end

next we will get some data from the viewportFrame, that we will need later

	local viewportSize = viewport.AbsoluteSize
	
	local camera = viewport.CurrentCamera ::Camera
	local fieldOfView = camera.FieldOfView
	local aspectRatio = viewportSize.X/viewportSize.Y

get the normalised X and Y position

ok now these steps will get a little more mathy. We can imagine the camera as an isosceles where:

  1. the angle of the “sharp part” is the field of view
  2. the flat part is the screen

we now want the normalised X and Y position. We will normalise the positions to (-1, 1) relative to viewportSize. The reason why it is (-1, 1) and not (0, 1) like normal roblox UI scale is cuz it make sense that 0 is something right in front of you. If somethign is right in front of your eyes, you do not need to move your head up or down. Thus (0, 0) is the normalised position in this case not (.5, .5).

	-- now we will get the normalised position(-1,1) of x and y
	local normalisedX = ((x/viewportSize.X) * 2) - 1
	local normalisedY = ((y/viewportSize.Y) * 2) - 1

next we will calculate the ray’s vector(relative to camera)

for this part, we will need the “Screen size” in the image provided on top. We can get it by doing

local opposit = math.tan(math.rad(fieldOfView)/2) * 1 --> tan = op/adj, we can assume adj is 1

next, we will get the relative direction of X and Y. Since we now have half the screen size, we can multiply half the screen size by the normalise position.

local relativeDirX = normalisedX * opposit
local relativeDirY = normalisedY * opposit

however, here comes a problem. I faced. the relativeDirX always seems to be wrong …
the issue is that the “Screen size” is only accurate for the Y axis. This is because the camera’s FOV verticle so it is actaully something more like this:


only for the verticle axis, the field of view will be accurate and the screen size will be correct. Thus, we will need to multiply relativeDirX by aspect ratio

local relativeDirX = normalisedX * aspectRatio * opposit

##reuturning a ray
ok, currently, the directions we have are relative to the camera. We can do this by using cf:VerctorToWorldSpace(vec)

local rayDir = camera.CFrame:VectorToWorldSpace(Vector3.new(relativeDirX,-relativeDirY, -1).Unit) 

there is a -1 in the z axis because -1 in roblox is front. Also, the 1 value is why we can assume adj is 1 in this part.
Also, do note that Y is inverted for some reaon lol

local opposit = math.tan(math.rad(fieldOfView)/2) * 1 --> tan = op/adj, we can assume adj is 1

lastly, we will return a ray

return Ray.new(camera.CFrame.Position, rayDir)

now time to piece this function together! I hope this makes sense and please ask any questions if you have (or if your function dont work, please send me your function for me to look through)

video of the working function:

this is my test script btw :smiley:

mouse.Button1Down:Connect(function()
	local viewportPosition = script.Parent.ViewportFrame.AbsolutePosition
	local relativeMouseX,relativeMouseY = mouse.X-viewportPosition.X,mouse.Y-viewportPosition.Y
	local ray = ViewportPointToRay(script.Parent.ViewportFrame,relativeMouseX,relativeMouseY)
	
	game.Workspace.ViewportFrameWorldModel.Attachment.WorldPosition = ray.Origin
	game.Workspace.ViewportFrameWorldModel.Attachment1.WorldPosition = ray.Origin + ray.Direction * 500
	
	local raycast = workspace:Raycast(ray.Origin,ray.Direction * 1000, params)
	print(raycast and raycast.Instance or "nil")
end)

click detectors dont works on viewport

ooo cool, I have finished reading it and will try to put it into practice. :smiley:

Yes, it worked! However, I have a question: sometimes it detects the world model. Is this normal?

I will send you the script if you need to see it.:
local function ViewportPointToRay(viewport: ViewportFrame, x: number, y: number)
local viewportSize = viewport.AbsoluteSize
local camera = viewport.CurrentCamera
local fieldOfView = camera.FieldOfView
local aspectRatio = viewportSize.X / viewportSize.Y

	-- normaliza de (0 -> size) para (-1 -> 1)
	local normalisedX = (x / viewportSize.X) * 2 - 1
	local normalisedY = (y / viewportSize.Y) * 2 - 1

	-- tamanho "virtual" da tela baseado no FOV vertical
	local opposite = math.tan(math.rad(fieldOfView) / 2)

	-- direção relativa à câmera
	local relativeDirX = normalisedX * aspectRatio * opposite
	local relativeDirY = normalisedY * opposite

	-- converte para world space
	local direction = camera.CFrame:VectorToWorldSpace(
		Vector3.new(relativeDirX, -relativeDirY, -1).Unit
	)

	return Ray.new(camera.CFrame.Position, direction)
end


local function GetClickedModel(part)
	while part and not part:IsA("Model") do
		part = part.Parent
	end
	return part
end

UserInputService.InputBegan:Connect(function(input)
	if input.UserInputType ~= Enum.UserInputType.MouseButton1 then return end

	-- posição correta do mouse
	local mousePos = UserInputService:GetMouseLocation() - GuiService:GetGuiInset()

	-- ViewportFrame é fullscreen
	local ray = ViewportPointToRay(
		ViewPortFrame,
		mousePos.X,
		mousePos.Y
	)

	local params = RaycastParams.new()
	params.FilterType = Enum.RaycastFilterType.Include
	params.FilterDescendantsInstances = { ViewPortFrame.WorldModel }
	params.IgnoreWater = true

	local result = ViewPortFrame.WorldModel:Raycast(
		ray.Origin,
		ray.Direction * 1000,
		params
	)

	if result then
		local model = GetClickedModel(result.Instance)
		if model then
			print("Model clicado:", model.Name)
			--MorphRemote:FireServer(model.Name)
		end
	end
end)

btw Thank you so much for sharing the script you made. I definitely couldn’t have done that myself, as I’m still a bit of a beginner.

Hmm, can you share with the the Instance in the viewport frame?

can i see what is under CharSelection.WorldModel.Positions? If it is basePart, then the reason for that behaviour is cuz at

you call the function GetClickedModel() which keeps going up the hierarchy until the child’s ancestor(parent.parent…) is a model. If CharSelection.WorldModel.Positions stores baseParts, the closest ancestor of the basePart will be CharSelection.WorldModel. You can instead fire result.Instance.Name if the basePart’s name is the character name. I hope this helps!

oooo i see the problem now

I fixed the problem, again, thank you very much.

yayy! Please mark my post as solution so that others facing the issue can easily find a fix! Thank you!

also, a better way to get the first ancestor that is a model is

Instance:FindFirstAncestorOfClass(“Model”)

this should be more performant as it is a default Instance method writen in C++(which is faster than luau)