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

Getting mouse hit position with User Input Service?

Hi, I'm trying to get the mouse hit position, but without using the :GetMouse() function. As far as I know, the only way to get the "mouse hit" with user input service is casting a ray, but it doesn't return a result when there is no result instance. Do any of you guys know how to get the mouse hit position (mouse.Hit.p with :GetMouse()) with user input service? Thanks!

2 answers

local Mouse = game.Players.LocalPlayer:GetMouse()

game:GetService("UserInputService").InputBegan:Connect(function(i)
if i.UserInputType == Enum.UserInputType.MouseClick1 then -- forgot the name, check out enum.userinputtype
print(Mouse.Hit.p)
end
end)

2 comments

0

Hi Puppy, so basically I'm trying to get the mouse hit position WITHOUT the :GetMouse() function, so I want to get the mouse hit position with User Input Service. I'm not sure how to go about doing that. Thanks for your answer, though. I'm aware that you can use mouse.Hit.p from :GetMouse(), but I want to get the hit position using just User Input Service. Thanks!

0

You cannot get the mouse hit without the :GetMouse() function

You need to do raycasting from the 2D position of the mouse. To get the Mouse position in screen, you do

local UIS = game:GetService("UserInputService")

local MouseLocation = UIS:GetMouseLocation() --This function returns a Vector2 value, X and Y

Then you use an function from Camera called ScreenPointToRay, it returns a ray.

local RayMag1 = Camera:ScreenPointToRay(MouseLocation.X, MouseLocation.Y)

And make another ray from that ray, like this:

local NewRay = Ray.new(RayMag1.Origin, RayMag1.Direction * 2048)

Finally you will have to only find the hit part with FindPartOnRayWithIgnoreList or FindPartOnRay, depending if u want to ignore the character or not.

local Target, Position = workspace:FindPartOnRayWithIgnoreList(NewRay, {})

And there you go, that's all, I think.

function GetMousePoint(X, Y, IgnoreList)
	local RayMag1 = Camera:ScreenPointToRay(X, Y) --Hence the var name, the magnitude of this is 1.
	local NewRay = Ray.new(RayMag1.Origin, RayMag1.Direction * 2048)
	local Target, Position = workspace:FindPartOnRayWithIgnoreList(NewRay, IgnoreList)
	return Target,Position
end

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