Sorry, i misread the title.
You could use raycasting to find the nearest edge of the part, and you can cast rays in multiple directions from the NPCs position to find the cloest edge
Once you have the nearest edge you can calculate the drection vector from the npc to the edge and use this drection vector to determine the direction in which the npc should attack the player
What you could do is you could make a preset list of ray directions like this
local raycastDirections = {
Vector3.new(1, 0, 0),
Vector3.new(-1, 0, 0),
Vector3.new(0, 0, 1),
Vector3.new(0, 0, -1),
Vector3.new(1, 0, 1).unit,
Vector3.new(-1, 0, 1).unit,
Vector3.new(1, 0, -1).unit,
Vector3.new(-1, 0, -1).unit
}
here are some functions that use this
local function findNearestEdge()
local nearestEdgePosition = nil
local shortestDistance = math.huge
for _, direction in pairs(raycastDirections) do
local ray = Ray.new(npc.Position, direction * 100)
local hit, position = workspace:FindPartOnRay(ray, npc)
if hit then
local distance = (position - npc.Position).magnitude
if distance < shortestDistance then
shortestDistance = distance
nearestEdgePosition = position
end
end
end
return nearestEdgePosition
end
local function attackTowardsEdge(player)
local edgePosition = findNearestEdge()
if edgePosition then
local direction = (edgePosition - npc.Position).unit
-- Apply force or move NPC towards the edge to attack the player
-- Example: Apply a force to the player in the direction of the edge
local playerCharacter = player.Character
if playerCharacter then
local humanoidRootPart = playerCharacter:FindFirstChild("HumanoidRootPart")
if humanoidRootPart then
local bodyVelocity = Instance.new("BodyVelocity")
bodyVelocity.Velocity = direction * 50 -- Adjust the force as needed
bodyVelocity.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
bodyVelocity.Parent = humanoidRootPart
game:GetService("Debris"):AddItem(bodyVelocity, 0.1)
end
end
end
end
Although it’s a little basic, maybe this could give you an idea of how it would look