How would I stop this NPC wandering off the baseplate?

I’ve got my own following NPC and I’ve made it so it wanders off when a target is out of its range. However, when it wanders, it walks off the baseplate quite often, despite me trying to stop this by using math.clamp

Any fix for this?
Code:

function Wander()
	local Base = workspace.Baseplate
	local X = math.random(1,25) + HumanoidRootPart.Position.X 
	math.clamp(X, 1, Base.Size.X)
	local y = math.random(1,25) + HumanoidRootPart.Position.Y
	math.clamp(y, 1, Base.Size.Y)
	local z = math.random(1,25) + HumanoidRootPart.Position.Z
	math.clamp(z, 1, Base.Size.Z)
	local Character = script.Parent
	local Humanoid = Character.Humanoid
	Humanoid:MoveTo(Vector3.new(X,y,z))
	Humanoid.MoveToFinished:Connect(function()
		HasWandered = true
	end)
end

i’m pretty sure you can use raycast to determine if there is no objects in it’s way, also if you don’t edit some of it it might be on a tower like a building model that it’s purpose is to be placed there, it would be stuck there

So that would stop it just walking off

yes if you make the ray origin (the npc’s humanoidrootpart or head or torso whatever) then the ray direction (vector3.new(5, -math.huge, 5)) and make a raycast result and make it stop then go away from the edge

i have no experiences of raycast 50% yet but i think that would work

You could use pathfinding, as this will never jump off edges with no spot to land on unless the endposition is close enough but beneath the edge.

Alright, I’ll try that. Any other alternative solutions to using raycasting?

nope i havent learn all the APIs of raycasting but youll get it fixed

I never knew that. I generally thought that even if there was no spot to land on, the npc would still go there! Maybe i’ll try that too

btw, using math.clamp() the way you’re doing now doesn’t work. you should define/assign a variable with the variable you’re clamping. local A = math.clamp(B,varA,varB)

oops, my bad, i’ll fix that now. Just that I haven’t rlly experimented much with it