Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Getting mouse hit position with User Input Service?

Asked by 3 years ago

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

Log in to vote
0
Answered by
Pupppy44 671 Moderation Voter
3 years ago
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)
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! coolboya_3 0 — 3y
0
You cannot get the mouse hit without the :GetMouse() function NathanBlox_Studios 212 — 3y
Ad
Log in to vote
0
Answered by 3 years ago

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

Answer this question