Help moving players outside a part after a random teleport

Currently I am working on AI for one of my games. Whilst this AI is “sleeping” (not calculating any actual actions) I still want them to feel alive so I am teleporting them to a random position nearby as if they where wondering around after a set amount of time.

How can I ensure that if this model teleports inside of a part, it will auto correct itself into moving outside of a possible part that it could have teleported within? This model is just a normal roblox character rig.

I don’t think my code will be too useful as it is just moving the model around but I will leave it bellow either way.

Thanks in advance : )

local distance = (UNIT.goalInfo - UNIT.pos) + Vector3.new(math.random(-25,25),0,math.random(-25,25))
local newPos = CFrame.new(UNIT.pos) * CFrame.new(distance)
newPos = CFrame.new(newPos.Position,UNIT.goalInfo)
UNIT.pos = newPos.Position
humanoidRootPart.CFrame = CFrame.new(humanoidRootPart.CFrame.Position,UNIT.pos) 
humanoidRootPart.CFrame = CFrame.new(UNIT.pos) * humanoidRootPart.CFrame.Rotation
1 Like

I have no clue if this is at all reasonable, but we are about to find out.

local function createPart()
     local part = Instance.new("Part")
     part.Anchored = true
     part.CanCollide = false
     part.Transparency = 1 
     part.CFrame = newPos -- whatever position that you make, idk how your system works
     local partsIn = part:GetPartsInPart()
     if partsIn == {} then
         return part.CFrame
     end
     part:Destroy()
end

local check

repeat check = createPart() until check ~= nil
-- set your ai character to check
1 Like

Thanks, do you have any suggestions on finding the closest way out of a part if a collision is detected? Or does this already do that automatically?

1 Like

This just keeps creating a random position until the ai character is not in a part

1 Like

The only way I get a random CFrame though is if I place the part in a random place. While this may be helpful if the AI is completely random, my system has the characters have “goals” they “walk” towards. Because of this I would have to have limits on the random position of the part but then I run into the problem of how large should the limits be? If I have a 100x100x100 part its going to be harder to get out of than a 1x1x1 part.

Thanks for the advice either way : )

1 Like