PID Implementation

i have this function where it will calculate the angle and its speed needed to get to the target

function Static:MoveTo(target: Vector3)
    local diff = (target - self.FVector.Position).Unit
    local dist = (target - self.FVector.Position).Magnitude

    local dot = diff:Dot(self.FVector.CFrame.LookVector)

    local angle = math.deg(math.acos(dot)) - 90

    angle = angle > 90 and 90 - angle or angle

    self.constraints.Right.TargetAngle = angle
    self.constraints.Left.TargetAngle = angle

    local speed = self.MAX_SPEED

    if dist < self.DECELERATION_DIST then
        speed = self.MAX_SPEED * (dist / self.DECELERATION_DIST)
    end
    
    self.constraints.RR.AngularVelocity = -speed
    self.constraints.RL.AngularVelocity = -speed

    self.constraints.FR.AngularVelocity = -speed
    self.constraints.FL.AngularVelocity = -speed
end

and it’s not behaving as good as i expected. I heard about PID controller, and then I wrote this module

local Controller = {
    constants = {
        Kp = 1;
        Ki = .1;
        Kd = .1;
    };
    process = Vector3.zero;

    integral = Vector3.zero;
    derivative = Vector3.zero;
    prev_error = Vector3.zero
}

function Controller:update(setpoint: Vector3, dt)
    local err = setpoint - self.process
    local err_mag = err.Magnitude

    self.integral += err * dt
    self.derivative = (err - self.prev_error) / dt

    local output = self.constants.Kp * err + self.constants.Ki * self.integral + self.constants.Kd * self.derivative

    self.process += output * dt
    self.prev_err = err
end

return Controller

how would i implement the PID controller to the function?

nevermind, i figured it out, i found out that PID is pretty much Pathfinding-alike. I just need to call the update function and get its process property

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.