Help my entitie to change target, if it near the initial one

Hello, i want to order my entities to change target ( to go to entitie CheckPoint in fact) if the player or npc or physics object or ground/sky is too close… but i don’t know how to do it any idea?

[lua]
include(“shared.lua”)
AddCSLuaFile(“cl_init.lua”)
AddCSLuaFile(“shared.lua”)

function ENT:SpawnFunction( ply, tr)
local SpawnPos = tr.HitPos + tr.HitNormal * 5000
local ent = ents.Create( “Test” )
ent:SetPos( SpawnPos )
ent:Spawn()
ent:Activate()
ent:SetVar(“Owner”,ply);
return ent
end

function ENT:Initialize()

self.Entity:SetModel( "models/katharsmodels/vipermk2/vipermk2_shuttle.mdl" ) 

self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )

local phys = self.Entity:GetPhysicsObject()
if (phys:IsValid()) then
	phys:Wake()
	phys:EnableGravity(false)
	phys:EnableDrag(false)
	phys:EnableCollisions(true)
end
self.Entity:SpawnPoint()
self.Target = nil
self.SecurityIsActivate = false
self.HasTarget = false
self.SecurityDistance = 3200

end

function ENT:Think()

if !self.SecurityIsActivate then

local ents = ents.FindInSphere(self:GetPos(), 30000)
for _, target in pairs(ents) do
if target:IsValid() then

if target:IsPlayer() or target:IsNPC() and  target:Health() > 0 then
self.Target = target
self.HasTarget = true


    end
end

end

end
end

function ENT:FindCheckpoint()

if self.SecurityIsActivate then

for k,v in pairs(ents.FindInSphere(self.Entity:GetPos(),90000)) do
if (v:IsValid() and v:GetClass() ==“CheckPoint”) then
self.Target = v
else
self.SecurityIsActivate = false
end
end
end
end

function ENT:SpawnPoint()
for i = 1,1 do
local c = (math.random(5000,6000))
local pos = Vector(0, 0, c)
if util.IsInWorld(pos) then

local Met = ents.Create(“CheckPoint”)
Met:SetPos(pos)
Met:Spawn()
Met:Activate()
end
end
end

function ENT:PhysicsUpdate(phys,deltatime)

if self.HasTarget then

        local pos = self.Entity:GetPos()
		
		self.Direction = (self.Entity:GetForward()*700);
	
	
		local t={
			secondstoarrive = 1,
			pos = pos+self.Direction,
			maxangular = 5000,
			maxangulardamp = 10000,
			maxspeed = 1000000,
			maxspeeddamp = 10000,
			dampfactor = 0.5,
			teleportdistance = 7000,
			angle = ( self.Target:GetPos() - pos ):Angle(),
			deltatime = deltatime,
		}
		phys:ComputeShadowControl(t);

end
self.LastPos = self.Entity:GetPos()
end
[/lua]

my idea was to check if target was too close, under the SecurityDistance, self.SecurityIsActivate is activated, make the entity search the CheckPoint entity and make it as the new target… but it doesn’t seem working… Any Help?

I cant help you with your Error but to optimse your Checkpoint searching:

use ents.FindByClass because it uses much less Resources at ents.findinSphere and then check if it is in range.