Raycasting Troubles

I need to know why this isn’t working correctly. I’m trying to use raycasting to determine how far away the humanoid is (In this case I have the NPC humanoids named “Monster”) and deal damage depending on if they are close enough.

local function onTouched(hit)
	local character = hit.Parent
	local targetHumanoid = character:FindFirstChild("Monster")

	if targetHumanoid and isActivated then
		-- Use raycasting to check the distance
		local ray = Ray.new(sword.Handle.Position, (hit.Position - sword.Handle.Position).unit * 5)
		local part, position = workspace:FindPartOnRay(ray, character, false, true)

		if part and part.Parent == character and part.Parent:IsA("Model") and part.Parent.Name == "Monster" then
			-- Deal damage to the humanoid (client-side only)
			targetHumanoid:TakeDamage(10)  -- Damage the Monster will take (Differs by the sword)
		end
	end
end

Any help is appreciated

It helps if you tell us what part is not working exactly.

The function itself as a whole. Before I implemented the raycast it dealt damage but only if I was super close. Now it seems to not be working.

Have you tried print debugging? i.e you can check the state of your variables you’re checking in your if statement.

Yes, honestly I might have it structured wrong because I’m new to coding in lua.

What are you checking for hits? The handle of the tool?, i’d also check if
local targetHumanoid = character:FindFirstChild("Monster") this is actually found by printing it first. It has most likely something to do with the if statements at the end tbh

Yep I believe this is the issue. I think it’s trying to get the child of the player instead of the npc

If you want to know the distance between the player and the NPC you can also just use magnitude:

local magnitude = (handle.Position - hit.Position).magnitude
print(magnitude) -- 4
1 Like

Probably, when doing damage to others you should always make sure theres a check that ignores the player itself.

1 Like

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