Hello there!
Recently, I’ve been wondering how exactly move_and_slide() works.
Naturally, I checked the source code but for a lack of a better word, was quite intimidated. I understand that the amount of stuff this function does, especially with the options of the character controller involved, warrants this complexity. However, I still wanted to at least have a basic understanding of the function.
On a surface level, I understand that move_and_slide() can be “in some way” considered a “more advanced” version of move_and_collide() that moves the character by velocity, and then handles the collision with either a slide or a bounce.
So I wanted to recreate it in GDScript, but my results always ended up inconsistent with the actual implementation. So clearly, I am making a fundamental mistake somewhere.
Hence the question of this thread: How would an (approximate) move_and_slide() implement in GDScript look like?
And a more general question: Would it ever be “bad practice” to not utilize the default move_and_slide() ? I’m aware that most of the standard functions are faster than anything struck together in GDScript, but I am unsure if this applies here.
Why would you want to rewrite it yourself?
What’s something that you can’t do with the built-in implementation of this function that you need to create a custom one?
It’s mostly for my own understanding. At the moment, I wouldn’t for example know how to change the “bounce vs. slide” angle when my characterbody collides with something, or what I would need to do to make it so that the body retains full momentum on slide instead of losing some etc.
I also ran into some strange jitter issues occasionally, and without fully understanding the method, I don’t feel like I can efficiently resolve them.
move_and_slide() will not handle the collision with a bounce, only with a slide (it’s in the name). There’s a doc page that says exactly how to recreate it.
# using move_and_collide
var collision = move_and_collide(velocity * delta)
if collision:
velocity = velocity.slide(collision.get_normal())
# using move_and_slide
move_and_slide()
Anything you do with move_and_slide() can also be done with move_and_collide(), but it might take a little more code. However, as we’ll see in the examples below, there are cases where move_and_slide() doesn’t provide the response you want.
Somehow I ended up looking everywhere but the most basic of places!
Additionally, regarding the bounce I mixed something up on my end. I had implemented a bounce solution ages ago and somehow forgotten about it… and attributed its mechanics to move_and_slide()… woops.
Thank you so much for the doc link and clarification.