# VectorForce Glitches Out

So I’ve looked everywhere to find the solution for this but nothing helped. Basically I have a game where you have bots and they’re controled using VectorForce, sometimes they’ll go crazy and glitch out of the world, though there’s times when they work just fine, I’m gonna post both examples below and the code.

Working properly:

Glitching out:

``````function control(character, target)
local mass = character:GetMass()
local directionModify = (target.Position-character.Position).Unit
local direction = Vector3.new(directionModify.X, 0, directionModify.Z)
local targetVelocity = direction * speed
local differenceVelocity = targetVelocity - character.Velocity
if (character.Position-target.Position).Magnitude > 50 and target then
print(character.Name, 'is at least 50 studs away from', target.Name)
character.VectorForce.Force = differenceVelocity * mass * acceleration
else
print(character.Name, 'is close to', target.Name)
character.VectorForce.Force = Vector3.new()
end
end
``````

Seems to be happening on the wall, maybe try adding a barrier and/or have pathfinding (if any) avoid the walls

I could be wrong though, it’s hard to tell completely

are you doing this in a while loop or runservice?

Yeah, I’m doing it inside of a while loop

Probably because differenceVelocity becomes an unpredictably large value.

1 Like

i dont recommend pathfinding but A* is more preffered

Yeah that’s what I’m thinking as well, just not sure what kinda checks to do

It doesn’t have much to do with checks, but rather the math you use to calculate the force.

Could this be of use?

``````function Accelerate(accelDir, prevVelocity, acceleration, maxSpeed, deltaTime)
local projVel = prevVelocity:Dot(accelDir)
local accelVel = acceleration * deltaTime

if projVel + accelVel > maxSpeed then
accelVel = maxSpeed - projVel
end

return prevVelocity + accelDir * accelVel
end
``````

The function returns a new velocity after acceleration has been applied, so if using LinearVelocity is an alternative for you then I’d go for that.

However, I believe you could rewrite the function to get the acceleration directly to plug into the VectorForce (multiplied by the mass of course) without changing how you’re doing it already:

``````function GetAcceleration(accelDir, prevVelocity, acceleration, maxSpeed, deltaTime)
local projVel = prevVelocity:Dot(accelDir)
local accelVel = acceleration * deltaTime

if projVel + accelVel > maxSpeed then
accelVel = maxSpeed - projVel
end

return accelDir * accelVel / deltaTime
end
``````

Haven’t tested this.

Thanks, I’m gonna test it out now

Or just put a math.clamp on the maxSpeed.