Enemy NPC (MeshPart/CFrame) Flings on Slopes: Need Dynamic Y-Axis Movement

Summary of Issue

I am building a custom enemy NPC using a single MeshPart welded to a primary Part (named hitbox) that serves as the root. I have abandoned physics constraints (like LinearVelocity) for movement and am now using direct CFrame manipulation (inside RunService.Heartbeat) to ensure precise control over speed and path.

The horizontal (X/Z) movement is now working well, but when the NPC encounters any slope or terrain change, it begins to fling, jitter, or completely bug out.

This issue stems from the fact that I am currently setting a fixed Y-coordinate in the target position calculation, which causes the NPC to clip into or float above uneven surfaces. I need an elegant solution to dynamically detect the ground height and set the Y position for smooth traversal.

Details of the Setup

Enemy Structure:

  • Root: A transparent Part named hitbox (set as rootPart in the script).
  • Visuals: A MeshPart is welded to the hitbox using a WeldConstraint.

below is the full script of my mob:

local meshPart = mob:FindFirstChildWhichIsA("MeshPart", true)
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
if not meshPart then
	warn("No MeshPart found inside mob!")
	return
end
local Players = game:GetService("Players")
local systems = game:GetService("ServerScriptService").Systems
local stateService = require(systems.StateService)

local replicatedStorage = game:GetService("ReplicatedStorage")
local modules = replicatedStorage.Modules
local debris = game:GetService("Debris")



-- Create invisible anchor part
local primaryPart = script.Parent.hitbox
primaryPart.Transparency = 1
-- Attach anchor to mesh
local weld = Instance.new("WeldConstraint")
weld.Part0 = meshPart
weld.Part1 = primaryPart
weld.Parent = primaryPart


-- Optional: set PrimaryPart so you can use mob.PrimaryPart later


local mob = script.Parent
local moveRadius = 60
local moveSpeed = 16
local rootPart = primaryPart

if not rootPart then
	error("No root part or hitbox found for roaming logic")
end


local animationController = mob.AnimationController
animationController.Parent = mob

local walkAnimation = script.Walk
local runAnimation = script.Run
local roarAnimation = script.roar
local animationTrack = animationController:LoadAnimation(walkAnimation)
local runAnimationTrack = animationController:LoadAnimation(runAnimation)
local roarAnimationTrack = animationController:LoadAnimation(roarAnimation)




animationTrack:Play()
-- Make sure it's unanchored so it can move
rootPart.Anchored = false

local function getRandomPosition()
	local offset = Vector3.new(
		math.random(-moveRadius, moveRadius),
		0,
		math.random(-moveRadius, moveRadius)
	)
	return rootPart.Position + offset
end

local moveSpeed = 10
local detectionRange = 50
local function getNearestPlayer()
	local nearest = nil
	local shortestDistance = detectionRange

	for _, player in ipairs(Players:GetPlayers()) do
		if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
			local charRoot = player.Character.HumanoidRootPart
			local charHealth = player.Character.Humanoid.Health
			if charHealth <= 0 then -- will not chase if the player is dead
				return 
			end
			local distance = (charRoot.Position - rootPart.Position).Magnitude
			if distance < shortestDistance then
				shortestDistance = distance
				nearest = player
			end
		end
	end

	return nearest
end



local blockDetection
local function Raycast(rayOrigin, rayDirection)
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {mob} -- ignore itself
	raycastParams.FilterType = Enum.RaycastFilterType.Exclude

	-- Cast the ray
	local result = workspace:Raycast(rayOrigin, rayDirection, raycastParams)

	if result then
		--print("Hit:", result.Instance.Name)
		blockDetection = true
	else
		--print("No obstacle in front")
		blockDetection = false
	end
	
	return result
	
end





local function smoothStop(dir)
	runAnimationTrack:Stop()
	for i = 1, 10 do
		rootPart.CFrame = rootPart.CFrame:Lerp(
			CFrame.lookAt(rootPart.Position,dir), 
			0.05
		)
		
		RunService.Heartbeat:Wait()
	end
end

local function followPlayer(targetPlayer)
	animationTrack:Stop()
	if not stateService.checkState(mob,"mobAttack") then
		runAnimationTrack:Play()
	else
		runAnimationTrack:Stop()
	end

	runAnimationTrack:AdjustSpeed(2)
	local targetChar = targetPlayer.Character
	local targetRoot = targetChar and targetChar:FindFirstChild("HumanoidRootPart")
	if not targetRoot then return end

	while targetPlayer 
		and targetChar 
		and targetChar.Parent 
		and (targetRoot.Position - rootPart.Position).Magnitude < 200 
	do
		local lookAt = Vector3.new(targetRoot.Position.X, 3, targetRoot.Position.Z)
		if blockDetection then
			smoothStop(lookAt)
			break
		end

		local targetPos = Vector3.new(
			targetRoot.Position.X,
			4,
			targetRoot.Position.Z
		)

		local dt = RunService.Heartbeat:Wait()

		-- Move toward player
		local dir = (targetPos - rootPart.Position).Unit
		rootPart.CFrame = rootPart.CFrame + dir * (moveSpeed * dt)

		-- Smooth rotate
		
		local currentCF = rootPart.CFrame
		local targetCF = CFrame.lookAt(rootPart.Position, lookAt)
		rootPart.CFrame = currentCF:Lerp(targetCF, 0.01)
	end
end

local finishedWalking = false
local function moveTo(targetPos)
	local startPos = rootPart.Position
	local direction = (targetPos - startPos)
	local distance = direction.Magnitude
	local moveDir = direction.Unit
	local duration = distance / moveSpeed

	local startTime = tick()
	finishedWalking = false
	animationTrack:Play()

	local connection
	connection = RunService.Heartbeat:Connect(function()
		local elapsed = tick() - startTime
		if elapsed >= duration then
			rootPart.CFrame = CFrame.lookAt(targetPos, targetPos + moveDir)
			connection:Disconnect()
			finishedWalking = true
			return
		end

		local alpha = elapsed / duration
		local newPos = startPos + moveDir * (distance * alpha)

		local currentCF = rootPart.CFrame
		local targetCF = CFrame.lookAt(currentCF.Position, newPos + moveDir)
		local smoothCF = currentCF:Lerp(targetCF,0.1)

		rootPart.CFrame = CFrame.new(newPos, smoothCF.LookVector + newPos)
	end)

	-- ⏳ Wait until finished before returning
	repeat task.wait() until finishedWalking
end


RunService.Heartbeat:Connect(function(dt)
	if finishedWalking then
		animationTrack:Stop()
	end
	local pos = primaryPart.Position -- gyroscope
	local _, y, _ = primaryPart.CFrame:ToEulerAnglesYXZ()

	primaryPart.CFrame = CFrame.new(pos) * CFrame.Angles(0, y, 0)

	local rayOrigin = primaryPart.Position
	local rayDirection = primaryPart.CFrame.LookVector * 10
	--visualizeRay(rayOrigin,rayDirection)
	blockDetection = Raycast(rayOrigin,rayDirection)

end)
local firstTarget


roarAnimationTrack:AdjustSpeed(10)
local mobModel = mob["PFT7TOLW1O68QOYQM5AT957UC.10"]
local headBone = mobModel["Bone.003"]["Bone.004"]["Bone.006"]["Bone.006.001"]

local roarCD = false
local function roar()
	roarCD = true
	animationTrack:Stop()
	local roarSound = script.roarSound:Clone()
	debris:AddItem(roarSound,3)
	roarSound.Parent = primaryPart
	roarSound:Play()
	
	local roarVfx = replicatedStorage.Assets.EffectsMob.roar1:Clone() 
	local roarVfx2 = replicatedStorage.Assets.EffectsMob.roar2:Clone()
	
	roarVfx.Parent = headBone
	roarVfx2.Parent = headBone
	debris:AddItem(roarVfx, roarSound.TimeLength)
	debris:AddItem(roarVfx2,roarSound.TimeLength)
	
	roarAnimationTrack:Play()
	task.wait(roarSound.TimeLength)
	roarAnimationTrack:Stop()
	
	task.spawn(function()
		task.wait(20)
		roarCD = false
		
		
	end)
	
	
end

wait(2)


while task.wait(1) do
	
	targetPlayer = getNearestPlayer()
	if targetPlayer then
		if not roarCD  then
			roar()
		end
		animationTrack:Stop()
	


		moveSpeed = 40
		local targetRoot = targetPlayer.Character.HumanoidRootPart
		local lookAt = Vector3.new(targetRoot.Position.X,0,targetRoot.Position.Z)
		local currentCF = rootPart.CFrame
		local targetCF = CFrame.lookAt(rootPart.Position, lookAt)
		local rotationSpeed = 0.1 -- adjust for smoother/slower rotation
		rootPart.CFrame = currentCF:Lerp(targetCF, rotationSpeed)
		
		followPlayer(targetPlayer)
	
	else
		moveSpeed = 10

		runAnimationTrack:Stop()
		local pos = getRandomPosition()
		moveTo(pos)
	end
	
	

end


here is the part that im still finding the solution to the Y axis. currently i set the Y value to 4 as i dont know how to get the Y axis for movement. as the mob touches a slope it Bugs out and flings. this applies to the GetRandomPosition function too (both are set with fixed Y coords)

local function followPlayer(targetPlayer)
	animationTrack:Stop()
	if not stateService.checkState(mob,"mobAttack") then
		runAnimationTrack:Play()
	else
		runAnimationTrack:Stop()
	end

	runAnimationTrack:AdjustSpeed(2)
	local targetChar = targetPlayer.Character
	local targetRoot = targetChar and targetChar:FindFirstChild("HumanoidRootPart")
	if not targetRoot then return end

	while targetPlayer 
		and targetChar 
		and targetChar.Parent 
		and (targetRoot.Position - rootPart.Position).Magnitude < 200 
	do
		local lookAt = Vector3.new(targetRoot.Position.X, 3, targetRoot.Position.Z)
		if blockDetection then
			smoothStop(lookAt)
			break
		end
		local Y = getGroundY(rootPart.Position)
		local targetPos = Vector3.new(
			targetRoot.Position.X,
			4,
			targetRoot.Position.Z
		)

		local dt = RunService.Heartbeat:Wait()

		-- Move toward player
		local dir = (targetPos - rootPart.Position).Unit
		rootPart.CFrame = rootPart.CFrame + dir * (moveSpeed * dt)

		-- Smooth rotate
		
		local currentCF = rootPart.CFrame
		local targetCF = CFrame.lookAt(rootPart.Position, lookAt)
		rootPart.CFrame = currentCF:Lerp(targetCF, 0.01)
	end
end

one solution that comes to mind is raycasting the Ground Y position. im trying to make a deepwoken Ish movement for the mobs

im trying to get an elegant solution to my problem as i am quite new to scripting. if there is any framework for mobs with meshmodel it would be very helpful
https://www.youtube.com/watch?v=bZkSH9NClYk (video of the mob movement)

1 Like