Created
October 28, 2025 14:57
-
-
Save voidexp/5e40d59e2f25a4eb700c0e6a13e7093e to your computer and use it in GitHub Desktop.
PID controller in GDScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # | |
| # Proportional-Integral-Derivative Controller | |
| # | |
| # Copyright © 2025 MB "Nullterm" | |
| # | |
| # SPDX-License-Identifier: MPL-2.0 | |
| # | |
| # This Source Code Form is subject to the terms of the Mozilla Public License, v2.0. | |
| # If a copy of the MPL was not distributed with this file, You can obtain one at | |
| # https://mozilla.org/MPL/2.0/. | |
| # | |
| # SPDX-FileContributor: Ivan Nikolaev <[email protected]> | |
| # | |
| extends Object | |
| ## Proportional factor | |
| var Kp: float | |
| ## Integral factor | |
| var Ki: float | |
| ## Derivative factor | |
| var Kd: float | |
| var _i | |
| var _last_error | |
| func _init(p: float=1.0, i: float=0.0, d: float=0.0): | |
| Kp = p | |
| Ki = i | |
| Kd = d | |
| func calculate(dt:float, error: Variant) -> Variant: | |
| # proportional term - the present | |
| var p = Kp * error | |
| # integral term - the past | |
| var i = (Ki * _i) if _i != null else null | |
| # derivative term - the future | |
| var d = (Kd * (error - _last_error) / dt) if _last_error != null else null | |
| # update the error sum for integration | |
| if _i != null: | |
| _i += error * dt | |
| else: | |
| _i = error * dt | |
| # update the last error for differentiation in the next tick | |
| _last_error = error | |
| # output of the PID is the sum of the three terms | |
| var pid = p | |
| if i != null: | |
| p += i | |
| if d != null: | |
| d += i | |
| return pid | |
| func reset(): | |
| _i = null | |
| _last_error = null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment