How would I check if there is a character 15 studs in front of the direction the player is looking?

Hi DevForum,

The title is self explanatory, but I want to know how I can detect if there is any character 15 studs in front of the player’s HumanoidRootPart facing direction.

I tried using RayCasting for this, but I’m new to that and it didn’t go as planned. Here is my script:

local function raycastTarget()
	-- 4 studs



	local rayMagnitude = Vector3.new(0,0,-4) -- Distance in Studs

	local rayOrigin = HRP.Position
	local rayDirection = rayOrigin + HRP.CFrame.LookVector * rayMagnitude

	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {Character}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist


	local raycastResult = workspace:Raycast(rayOrigin, rayDirection)

	if raycastResult then

		if raycastResult.Instance.Parent:FindFirstChild("Humanoid") and raycastResult.Instance.Parent ~= Character then
			print("Found a humanoid!")

			warn(raycastResult.Instance)
			warn(raycastResult.Instance.Parent)
		end

	end
end
2 Likes

When calculating the raycast, automatically add the origin with the direction, change this

to this, and change rayMagnitude to number

local rayMagnitude = 4 -- Distance in Studs
local rayDirection = HRP.CFrame.LookVector * rayMagnitude
1 Like

If you really don’t wan’t to use raycasting, you can make part in front of player, that when touched by non owner character, detects hit

1 Like

Thanks for the solution, also @0786ideal , thank you, but it wasn’t really how I didn’t want to use raycasting, it was more of trying to experiment with it.

1 Like

If you really wan’t i can write you ray beetween part and 15 studs in front of this part

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