Raycasting not working as intended?

So here, I have a script from the server which is supposed to handle the requests of my meelee weapons. When I try check if it has hit anything, it consistently returns nil. I’m quite confused as it is supposed to detect the hitbox of the intended target.

local replicated_storage = game.ReplicatedStorage
local events = replicated_storage:WaitForChild("RemoteEvents")
local combat_event = events:WaitForChild("Combat")
local weapon_data = replicated_storage:WaitForChild("Weapons")

local function verify_distance(object,char)
	local humroot = char:WaitForChild("HumanoidRootPart")
	print(object)
	local ray = Ray.new(char:WaitForChild("HumanoidRootPart").Position,(object.HitBox.Position).Unit*500)
	local hit = game.Workspace:FindPartOnRayWithWhitelist(ray,{object.HitBox})
	print(hit)
end

combat_event.OnServerEvent:Connect(function(plr,object)
	local char = plr.Character
	local weapon = char:WaitForChild("Weapon")
	local debounce = weapon:WaitForChild("Debounce")
	local name = weapon.Name.Value
	if not debounce.Value then
		debounce.Value = true
		print("Recieved request")
		verify_distance(object,char,weapon)
		wait(0.3)
		debounce.Value = false
	end
end)
1 Like

The second parameter on the New Ray needs to be a Direction.

local ray = Ray.new(char:WaitForChild("HumanoidRootPart").Position,(object.HitBox.Position-humroot.Position).Unit*500)

You may also want to shorten the distance of the Ray. Shorter Rays are more performant.

Also, what is the point of this if you’re only checking the distance between the objects? You can do this with:

dist = (obj1.Position-obj2.Position).Magnitude
1 Like

The problem with magnitude is that it checks the distance between the center’s of objects, whereas I want to check the distance between the surfaces of objects. And yes, I will make the ray shorter, I was just a little confused while I was try to get this to work.