Gun Raycast not working as suppose


Here’s a video of the problem, the Dummy will turn red once it’s hit.
As you see a lot of times where there should’ve been a hit, it’s disregarded.

Here’s the Raycast script:

	local origin = Player.Character.Head.Position

	local Destination = Pos

	local direction = (Destination - origin)

	local ray = Ray.new(origin, direction)

	local hit, position = workspace:FindPartOnRay(ray, Player.Character)

	if not hit then
		print("no part hit " .. tostring(hit))
	end

	if hit then
		hit.Color = Color3.fromRGB(255, 25, 25)
	end
end)```

The Raycast fires from the Players Head to the Position of the mouse, which in this case is the Dot.

Thanks in advanced!

What is Pos here?

If you want to ignore certain parts and get a similar result to Mouse.Target I would use Mouse.UnitRay to define ray’s direction. Also, WorldRoot:FindPartOnRay() is deprecated, so instead you should check out new raycast function along with RaycastParams.

local Mouse, Range, Params
local UnitRay = Mouse.UnitRay
local Result = workspace:Raycast(UnitRay.Origin, UnitRay.Direction*Range, Params)
1 Like

The direction variable you created should be the Unit vector of the difference between the hit and the origin.

local direction = (Destination - origin).Unit

and then when raycasting, you can set a desired length for how far to raycast like so:

local distance = 250
workspace:Raycast(origin, direction * distance, RaycastParams)

EDIT: Never mind, figured it out, thank ya very much, this method is actually detecting every shot now!

Hey, worked pretty well, thanks for that there.
Quick question though, how would I get the specific Instance from the Ray?
Currently, if I print the Ray it’ll give me something such as

RaycastResult{Head @ -15.8301973, 4.43132448, -26.4420147; normal = 0, 0, 1; material = Plastic}

Pos came from the Players Mouse position through the fired event, I checked out the links too, they were a pretty big help, thank ya

Because the code sample I posted was using the newer Raycasting, you can just define it like so:

local direction = (Destination - origin).Unit
local distance = 250
local raycastResult = workspace:Raycast(origin, direction * distance, RaycastParams)

if raycastResult then -- we hit something
    print(raycastResult.Instance.Name) -- what you want
end

You can also get other things such as:

  • Position hit (raycastResult.Position)
  • The surface normal (raycastResult.Normal)
  • Material of the part hit (raycastResult.Material.Name)
1 Like