How Do I Make Ray Get Casted Onto 1st Humanoid

  1. What do you want to achieve?
    so the ray cast hits 1st humanoid than so on and so on bc im trying to make td game so I can’t have it random
  2. What is the issue?
    I don’t know how to make it not random
  3. What solutions have you tried so far?
    I tried looking it up in the internet and nothing popped up so yeah

this is my ray cast script

	for i,v in pairs(game.Workspace.Enemies:GetChildren()) do
		local enemy = v:FindFirstChild("Humanoid")
		local torso = v:FindFirstChild("Torso")
				
		if enemy and torso and enemy.Health > 0  then
			if idleanim.IsPlaying then	
			else
				idleanim:Play()

			end
			
			
			if (torso.Position - script.Parent.Parent.Torso.Position).magnitude < range then
				
				local ray = Ray.new(script.Parent.Parent.Torso.Position, (torso.Position - script.Parent.Parent.Torso.Position).Unit * range)
				local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(ray, {turret,script.Parent.Parent})
				if hit.Parent:FindFirstChild("Humanoid") then
					shooted = enemy
					target = torso
				else
				idleanim:Play()
				end

I just need a way for it to find 1st enemy not random one

It’s not really random. The issue here is that you’re acting on the first Humanoid that matches the condition of your search rather than the “first Humanoid”, which I assume you mean instead “the closest Humanoid to the tower”.

You should be updating the nearest character variables based on if another iterated object in the for loop is closer or not. Since you don’t and only act on whatever meets the criteria first, likewise, it’ll never actually get to the closest object, just anything that passes.

-- This is your constant
local SEARCH_DISTANCE = 14 -- Range

-- These get defined with every new search
local currentRange = SEARCH_DISTANCE
local currentTargetHumanoid, currentTargetRoot

for _, enemy in ipairs(enemies) do
    -- Get enemy HumanoidRootPart and Humanoid; if none exist, use continue
    -- Get the magnitude of the HumanoidRootPart's distance from the tower
    -- If the magnitude of distance is less than currentRange:
        -- Set currentRange to that magnitude and fill the rest of the currents
    -- Repeat for all enemies in the list
end

-- At the end of the for loop, you should now have the closest enemy
-- NOW you can act on them, casting a ray to action on them

This is not code, this is guidance. Please feel free to use documentation and some testing to fill in the blanks if you need. You can also reference some free resources in the toolbox for distance scripts and adapt them into your targeting system.

2 Likes

thanks that helped alot thanks for explaining how it actualy worked cuz tutorial i used on railcasting didn’t rlly explain it. thanks again for the help