godotengine / godotengine/godot-docs
Confusing velocity variable in "2D movement overview"
- Dominant language
- reStructuredText
- Stars
- 5.7k
- Forks
- 3.8k
- Avg merge
- 1d 20h
- Merged PRs (30d)
- 25
Description
**Your Godot version:** N/A
**Issue description:**
The page shows examples of various 2d moving schemes implementations. I will focus on "8-way movement" but most others have similar problem.
_The problem:_
The code snippet first declares `velocity` as a global (in this script) variable and at the end of `_physics_process` assigns the return value of `move_and_slide` to that variable: `velocity = move_and_slide(velocity)`.
But then the first thing it does in `_physics_process` is `getInput` that immediately overwrites this variable with `Vector2()`, so first of all assignment `velocity = move_and_slide(velocity)` does basically nothing and second of all there is no need to make `velocity` global (`getInput` should just return it).
_Why is this a problem:_
As a complete beginner with Godot, I heard somewhere that the return value of `move_and_slide` is important and I was trying to understand how to use it in this "8-way movement" setting.
When I looked at the code and noticed that `velocity` is global and gets assigned the return value of `move_and_slide` I immediately assumed that there is something I don't yet know about GDScript and that this variable is expected by the KinematicBody to be there (and used somewhere outside of `_physics_process`). After reading [KinematicBody2D's code](https://github.com/godotengine/godot/blob/67e4082b1e73f3cbe518c499eb328b0f68f3419b/scene/2d/physics_body_2d.cpp#L997) and some experimentation I believe this is not the case (am I right?) - the code is simply written strangely? (maybe because in cases like [platformer movement](https://docs.godotengine.org/en/stable/tutorials/physics/using_kinematic_body_2d.html#platformer-movement) it actually makes sense?)
_How to fix it:_
If there is actually no need for `velocity` to be global and have the return value of `move_and_slide` assigned - then either rewrite the code so `velocity` is simply returned from `getInput` or explicitly explain why this might be useful in future.
If there is a reason for the code to be written in such a way (eg. that `velocity` is actually used somewhere else) - explain it explicitly.
This way people like me will not need to spend time going through the engine code (finding no good answers).
**URL to the documentation page (if already existing):** https://docs.godotengine.org/en/stable/tutorials/2d/2d_movement.html#doc-2d-movement
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.