Help when raycasting to mouse position

Hey there.

I know this has been posted several times, but my script doesn’t seem to be working quite fine and I don’t know why really. I want to create a tool you can use to push away players. The logic is the following:

  1. A raycast is shoot to wherever the mouse is.
  2. If there is a player there, add velocity * the localplayer’s look vector.

But what’s wrong here?

local UIS = game:GetService("UserInputService")

local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

local Camera = game:GetService("Workspace").CurrentCamera
local Params = RaycastParams.new()

local Whitelist = { }

for I, Player in pairs (Players:GetPlayers()) do
        if Player ~= LocalPlayer then
                Whitelist[I] = Player
        end
end

Params.FilterDescendantsInstances = { Players } -- Anything you want, for example the player's character, the ray filters through these
Params.FilterType = Enum.RaycastFilterType.Whitelist -- Choose whitelist or blacklist

function RayResult(X, Y)
        local UnitRay = Camera:ScreenPointToRay(X, Y)
        return game:GetService("Workspace"):Raycast(UnitRay.Origin, UnitRay.Direction * 2, Params) -- 500 studs
end

UIS.InputEnded:Connect(function(Input, GameProcessed)
        if not GameProcessed then
                if Input.UserInputType == Enum.UserInputType.Touch or Input.UserInputType == Enum.UserInputType.MouseButton1 then
                        RayResult(Input.Position.X, Input.Position.Y)
                        print(RayResult(Input.Position.X, Input.Position.Y))
                end
        end
end)

Could you elaborate on “not working quite fine” means?

i think he means not working well

When I do print(RayResult()), it prints nil. Maybe it isn’t going to the mouse position. Maybe the Ray isn’t being created. I’m not sure, that’s why I ask.

You are whitelisting the players and not the player character. Also, if a player respawns it won’t work since it won’t add them to the list so you should probably change some of that.

I was testing something. I tested it with a nil blacklist and still nothing.

I thought it was whitelisting them? You should change this to Blacklist.

I’m saying I did. The script I published here was after doing my tests.

Okay, what is the distance of UnitRay.Direction? Try changing UnitRay.Direction * 2 to UnitRay.Direction * 1000.

1 Like

The ray is being created, it only has a length of 2 studs though from the screen so it likely isn’t long enough to hit anything. Change its length to be some larger number instead of 2

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.