My ray doesn't always hit?

Hey! I’m working on a first person shooter game and I came across this weird thing. Basically , I’m using raycasting to detect if a player was hit. When I shoot at someone, the ray doesn’t always hit the player. The player has to be really close to me or be standing still for the ray to actually hit him. Any help would be very appreciated! :wink:
Code:

local RayCast = Ray.new(					
bruh, -- vector3 of the mouse
(ToP-bruh).unit*500
)
local Part,Position,Normal = game.Workspace:FindPartOnRay(RayCast,plr.Character, false,true)
if Part then
print(Part.Name)
local Dist = (ToP-bruh).magnitude
if not Dist then Dist = 300 end

What does ToP describe? Line 3

It’s the UpperTorso’s Vector3 (30 character limit)

Should I use mouse.Target instead?

Why are you subtracting it then? Why not just use Mouse.Hit? Or Mouse.Hit.P

Mouse.Target returns a basepart in which the mouse is over.

Unlikely problems

First off, the if statement never matched a end. I assume this is because part of the code is cut off. Secondly, the Dist variable is never used. I assume this is also because of code cutoff.

The likely problem

The way you are creating the ray will offset it weirdly. You want to start the ray at the location of the player, not that of the ground. The first parameter is the Orgin, or start of the ray. The second parameter is the Direction, or where you want the ray to face and how far to go. Try using the below instead:

local mouse = game.Players.LocalPlayer:GetMouse()
local RayCast = Ray.new(					
ToP, --Position of torso origin 
(mouse.UnitRay.Unit)*500 --Towards the location the mouse is pointing
)
local Part,Position,Normal = game.Workspace:FindPartOnRay(RayCast,plr.Character, false,true)
if Part then
print(Part.Name)
local Dist = (ToP-bruh).magnitude
if not Dist then Dist = 300 end
end --Add if there is not one below the cutoff
1 Like