Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to Raycast from the Players Torso/HumanoidRootPart?

I'm creating a detection feature for an attack however I need to figure out how to detect if someone is standing in front of the player, I would use touched() however this is buggy

I would provide sample code but I'm clueless, how can I do this properly?

ray = Ray.new

1 comment

0

I suggest you use the magnitude of hrp.Position-nearTorso.Position and calculate the angle of the vector to determine if someone is in front of you using the humanoidrootpart rotation as the normal

1 answer

✓ Accepted answer

Server Script

game.Players.PlayerAdded:Connect(function(Player)
	Player.CharacterAdded:Connect(function(Character)
		local root = Character:WaitForChild("HumanoidRootPart")

		local ray = Ray.new(root.CFrame.p, root.CFrame.lookVector * 500)
		local hit, hitposition = workspace:FindPartOnRay(ray, Character)
		
		if hit.Parent:FindFirstChild("Humanoid") ~= nil and (root.Position - hitposition).magnitude <= 50 then
			print("Humanoid Near Me!")
		end
	end)
end)

Local Script Variant

local player = game.Players.LocalPlayer
repeat wait() until player.Character ~= nil and workspace:FindFirstChild(player.Name) ~= nil
local character = player.Character
local root = character:WaitForChild("HumanoidRootPart")

local ray = Ray.new(root.CFrame.p, root.CFrame.lookVector * 500)
local hit, hitposition = workspace:FindPartOnRay(ray, character)

if hit.Parent:FindFirstChild("Humanoid") ~= nil and (root.Position - hitposition).magnitude <= 50 then
	print("Humanoid Near Me!")
end

EXPLANATION

The above scripts create a ray immediately after the player's character is created.

The first argument in creating a Ray is the origin (the starting position)

The second argument is the direction of the Ray (the CFrame.lookVector will determine the face of the humanoidrootpart)

The *500 is the overall distance the Ray can travel from the origin

workspace:FindPartOnRay determines the ray in the first argument and what it will ignore in the second

The local hit, hitposition are the hit parts and their Position Vector

To determine if a part the ray hit is under another player / npc we check that the Humanoid of the parent model is not nil

We can use .magnitude to determine the distance between the HumanoidRootPart Position and the "hitposition" (in this example, 50 is the distance you want them to begin an action)

For information regarding attacking, you can check out Animations here: http://wiki.roblox.com/index.php?title=Animations

Comment below with any questions or concerns, or if you can't figure something out.

This discussion is preserved as it was. New answers, comments, and votes are closed.