So in this code i understand that "move_and_slide_with_snap()" returns the 'y' component of a Vector2D and moves the character. My question is in trying to understand the logic of the movement and why it works. Do we return the y component first and then move the character or what is the 'algorithm' of the move and slide function? As it was weird to me that we needed to return the y component of the vector at all.
Here's what's happening.
A function takes some parameters, makes some calculations, and optionally returns a value.
move_and_slide_with_snap() takes some parameters, starting with a velocity, makes some calculations, moves your characters, and it returns a modified velocity.
That modified velocity is the remainder of the character's movement after collisions like hitting the floor (can reduce the Y velocity to 0), hitting a wall (can reduce the X velocity to 0), or any other collision.
The function returns that new velocity, but unless we store it in a variable, the returned value is lost.
That's why we write _velocity.y = move_and_slide_with_snap().y
The ".y" makes it so we extract the Y component of the returned velocity vector and assign it to the Y component of our _velocity variable. Now, why do we have this ".y" on either side of the equal sign?
Well, in this game, the enemies move at a fixed horizontal speed. When they hit a wall, we multiply their horizontal velocity by -1 to change their movement direction. This makes them move like the Goombas in Mario.
If we applied the returned X velocity from move_and_slide_with_snap(), when the enemies hit a wall, their X velocity would be reduced to 0, and they would stop moving entirely.
That's why we only override our _velocity.y variable.
But the important part is that the move_and_slide_with_snap() function calculates and returns a new velocity, and that, depending on your needs, you can save that value, be it entirely or just one vector component.
Thank you so much, this helps me understand it way better than before. Thank you for telling me that when a collision happens (in x or y), it can reduce (x or y) to zero. I needed to know that for it to make sense, thank you so much and I appreciate the work you put in for creating these courses :)