Making NPCs see in a "Tile"/"Block"/"Lane" sight?

If you’ve played the game “Plants vs Zombies” before, there are “towers” that can shoot whenever a zombie infront of them.
Plants vs Zombies is a lane-styled tower defense game.

My current code is simply in these steps:

  1. Finding the lane the tower is in.

  2. Check if the lane is not empty.

  3. Get the enemies inside the lane

  4. Check if the distance is lower than the range. (flawed)

    local laneSelected : Folder = workspace.Enemies[config.LaneDefend.Value]
    
    if (#laneSelected:GetChildren() > 0) then
    	for _, enemy : Folder in pairs(laneSelected:GetChildren()) do
    		local Distance = (tower:FindFirstChildOfClass("Model").PrimaryPart.Position - enemy:FindFirstChildOfClass("Model").PrimaryPart.Position).Magnitude
    		if Distance <= config.Range.Value then
    			return true
    		else
    			return false
    		end
    	end
    else
    	return false
    end
    end
    
    

My issue is towers would shoot even if an enemy is behind them and would like replace the code with the tiles as a term of range. Any form of help would- well… Help.

Use a RayCast.

Or ShapeCast if the enemies are in a different height of the tower.

The direction will be something

local range = 50
local direction = PrimaryPart.CFrame.LookVector * range

Sorry for not helping more, I am on phone right now.

2 Likes

Thank you, this BASICALLY just made my entire game.

1 Like

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