How do I cast a ray from my character's torso to a target infront of it?

I have 2 characters, one which is controlled by the player and one dummy
if the player clicks, a punching animation appears
problem is I can’t get a raycast to work properly, I want it to check for any target within 5 studs infront of my torso and if it finds any, to deal damage

local Character = Fist.Parent
	local Torso = Character:FindFirstChild("Torso")
	if Torso then
		local RaycastResult = workspace:Raycast(Torso.Position,, 0, Torso.CFrame.LookVector.Z+5))
		if RaycastResult then
			print("Instance:", RaycastResult.Instance)
			print("Position:", RaycastResult.Position)
			print("Distance:", RaycastResult.Distance)
			warn("No raycast result!")
		if RaycastResult and RaycastResult.Instance and RaycastResult.Instance:IsA("Model") then
			local TargetHumanoid = RaycastResult.Instance:FindFirstChildOfClass("Humanoid")

One thing I would say to make sure you properly filter out your player so you dont “hit yourself” with your own ray, using RaycastParams, and its Property FilterDescendantsInstances, RaycastParams is just used to modify the Ray to your Liking, and what it can do in the world, you can view that information here.

Params = -- New Params
Params.FilterType = Enum.RaycastFilterType.Exclude 
-- Makes the Ray Blacklist Specific Objects (which just means to ignore them)
Params.FilterDescendantsInstances = {Character}
-- In this case your character
-- so you dont hit yourself on accident

When trying to cast in front of the Player, you need to Multiply the LookVector by a specified amount, LookVector is basically the Direction you are facing, Multiplying it will be like adding Range to that Direction, in this you are trying to have the range of 6 (LookVector is Normalized, which basically means the Positions are in Between 0 and 1), so you would multiply the LookVector by 6.

When Raycasting, Your First Argument is your Torso Position, Second Argument is your LookVector * 6, The Third Argument is your RaycastParams

workspace:Raycast(Torso.Position, Torso.CFrame.LookVector * 6, Params)

You only need to check for a RaycastResult, and nothing else here, if your Ray didnt hit something, it will not give you a result at all, are are also checking the Instance the Wrong way, The Ray will return the Object that it hit as in a Part, not the Entire Model, for that you need to check the Parts Ancestry using :FindFirstAncestor(), or :FindFirstAncestorOfClass(), or even :IsDescentanrOf(), from there you can check whether to Damage the Player or not

1 Like

Maybe try using magnitude instead, so try using workspace:GetDescendants(), Do a for loop on it and remove all of the items without a child with the class of Humanoid (this will give you a table of all character models) then for each one of those subtract it’s torso position with the players torso and use the new subtracted vector3.magnitude and check if that is below 5.