Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Can't get the mouse's target using UserInputService, CurrentCamera, and RayCasting?

What the script does is it takes the UserInputService's mouse position on screen and then uses it to make a ray pointing from the camera, and then trys to use raycasting, but for some reason it isn't working

function getMouseTarget(mousePos)
	local ray = workspace.CurrentCamera:ScreenPointToRay(mousePos.x, mousePos.y, 1000)
	return workspace:FindPartOnRay(ray)
end
print(getMouseTarget(game:GetService("UserInputService"):GetMouseLocation())

this prints out nil, Vector3, nil, Enum.Material.Air which means it isn't hitting a block even though I knew it should have hit one. I've also tried running this while the camera had been inside a block.

What I've found on it but doesn't seem to work:

This says it worked they got an answer, but when I tested it in my game and when I tested it in a script builder it didn't work:

http://scriptinghelpers.org/questions/27647/is-there-a-simple-way-to-get-mouse-hit-position-from-its-screen-coordinates-actually-solved

This also has an answer in the forum that's almost identical, but also doesn't seem to be working:

http://devforum.roblox.com/t/new-mouse-input-query-methods/41304

2 comments

0

I've tested the code in Voidacity's Script Builder and in my actual game and for some reason it won't hit objects

0

mouse.Target. simple as that lol

3 answers


function getMouseAndTargetLocation(cursorPosition)
    local ray = workspace.CurrentCamera:ScreenPointToRay(cursorPosition.x, cursorPosition.y, 1)
	ray = Ray.new(ray.Origin, ray.Direction * 999)
    print(workspace:FindPartOnRay(ray))
end
getMouseAndTargetLocation(game:GetService("UserInputService"):GetMouseLocation())

Solution requires ending ScreenPointToRay with 1 and then making a new ray from with with a longer direction

This is what I use

local uis = game:GetService("UserInputService")
local mouse = uis:GetMouseLocation
local cam = workspace.CurrentCamera
local length = 100

local function mousepos(mousepos: Vector2): Vector3
	if mouse then
		local unitray = cam:ViewportPointToRay(mousepos.X, mousepos.Y, 0)
		local rayresult = workspace:Raycast(unitray.Origin, unitray.Direction * length)
	end
end

You can use :GetMouse().Target, like this

print(game.Players.LocalPlayer:GetMouse().Target:GetFullName)

Thats just what I think you should use.

1 comment

0

UIS is taking over mouse functions, just better to use cause they might delete it (I think its already deprecated

This discussion is preserved as it was. New answers, comments, and votes are closed.