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.
1 comment
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