I just got started with Godot recently and I've spent the last 3 days in a state of frustration for not being able to get my character to play nice with slopes. Other tutorials I tried all failed, I read the documentation for move_and_slide_with_snap over and over again - couldn't figure it out. Thanks for this video, if it wasn't for you I wouldn't have ever thought of using move_and_slide_with_snap only on the y component of velocity. Frankly, I still don't understand why that still works at all, but I'm not about to question it. Great stuff, good vibes, definitely subscribed, thanks a million Mr. Pigdev
"floor max angle" makes perfect sense though. It defines the maximum angle of what's considered to be a floor by move_and_slide. Anything steeper is considered a wall.
In case anyone is having trouble jumping, I had to set the snap vector to zero beforehand. Something like: snap_vector = SNAP_DIRECTION * SNAP_LENGTH if Input.is_action_just_pressed("jump") and is_on_floor(): snap_vector = Vector2.ZERO is_jumping = true
While this is a helpful video, I'd urge everyone to be careful with how they implement velocity. In this tutorial, it seems to me that the character ends up running much faster up the slope than on flat ground. This happens when the X Speed is preserved regardless of the movement angle. For more natural slope movement, it's better to preserve the overall velocity. This isn't a rule by any means, but it's good to know so that you can be more intentional with how you code your movement.
Working with radians is easy: Every value you want is simply some fraction of TAU. As a baseline, TAU itself is equal to 360°, so just pretend that every mathematical operation you apply to TAU is being applied to 360 to figure out what it would look like in degrees. 3 * TAU / 4 == 270° TAU / 2 == 180° TAU / 4 == 90° TAU / 6 == 60° TAU / 8 == 45° TAU / 16 == 22.5° TAU / 24 == 15° Any simple math using only constant numbers like this in any const definition will be precompiled into the script to become a proper floating number, and not take any processing time while your game is running. The "deg2rad" function you use simply does something like "deg * TAU / 360" to return some fraction of TAU.
So so basically...45*(360/360)? What's the advantage of that, apart from the floaring numbers compilation you've mentioned? I mean, in run time it can't pre compile.
@@pigdev TAU is actually 2 * PI, so 1 TAU is 360 degrees, but in radians (6.2831853071...), not literally 360. So the math here is really more like "(45.0 / 360.0) * TAU" for "45 out of 360 turned into radians", but I changed the order of operations because I am an old school C programmer who is used to working with integer math and fixed-point operations, eg. so you have to multiply before you divide or else you would lose precision. :P If you use "deg2rad(45)" in a const, I think it would be the same thing as "45.0 / 360.0 * TAU" anyway, and maybe optimized, but the PURPOSE is that I like the look of "TAU / 8" more because it directly and plainly means "1/8th of a circle" instead of some number "45", and the math is simple enough to be readable.
@@JessieEchidna ohh, I find it harder to get stuff like...48 degrees or these kind of specifc values. But I think I got the idea, for some it is easier to think of, e.g. TAU/4, I think that it can be useful for writing things in term of circles. E.g. 2*TAU is easier to write and understand that it is 2 spins than 720 degrees
Ahhh! So the trick is updating the vertical parameter of Velocity only! God, I'm suffering with slopes for months! If you don't mind, I didn't really understand why that solves the problem here. Could you elaborate more? Also, does it work when you walk across (downward or upward) tiles with different inclinations? (Like terrain from Megaman Zero, where steepness can change across the same floor/tile segment) And have you tested it with curved terrain like loops or semi loops? And finally if I may ask: the "velocity.Y = move_and_slide().Y" trick works on Godot 4.0 too?
So you wanna tell me that I spent more than 30 hours in unity to get the movement kind of working and godot has it basically built in!? I am so switching to godot. Thanks for the video!
I think you can change the floor normal and the snap normal to snap the character to the loop you can basically take the collision normal and use it as the floor normal and invert it to use as the snap normal
Hi Pigdev, what if i want the character to go down the slope like the angle in ur video thumbnail? i dunno how to make the character slide down with its position parallel to the slope.
Hey! Follow me on twitter heh, I've made a small written tutorial explaining that in my experiments project. Check it out: pigdev.itch.io/experiments/devlog/158787/tilting-on-slopes
Hey Pigdev, do you know how ''slopes'' are handled in stuff like old top-down Zelda? It seems like different places can have different simulated Z values, leading arrows and even the more complex arcing bombs etc. to collide or pass when shot/thrown, but these little transitions acting as abstractions of slopes where you simply walk or shoot straight projectiles between different heights as if nothing changed make me feel Z differences are calculated based on obstacles that have nothing to do with the then presumably singular ground layer. (Those bombs might even add x/y if z destination is lower and vice versa, idk)
would you be able to make a 3d tutorial for this? I've been trying to make a 3d kinematic player but I can't seem to get the move_and_slide_with_snap() func to work as it does in your video. Currently I have to give up because I'm still too much of a newb to figure out if my code is just broken or if v3.4 actually has bugs
I also thought of that before and tried to set gravity = 0 (instead of maybe using false or something)...and my character just floated up and did not stop :') I'm sure I was just missing something, but it was funny to watch!
Cara, parabéns e obrigado pelo ótimo trabalho. Venho pedir que vc faça um tutorial completo de plataforma 2d. Pois eu estava seguindo o curso do BornCG, é muito bom, tudo funcionando, mas ele não ensina combate, nem slope, nem como botar online multiplayer, nem dash etc. E toda vez que eu tento implementar codigos de outros tutoriais NÃO FUNCIONA. Eu tentei usar o teu codigo, mas no meu já tá com um monte de finite states, muita coisa interligada, então não funciona. Um curso completo ainda não existe, então poderia fazer muito sucesso, pois a maioria dos professores em inglês fala muito rápido e as pessoas de outros países não entendem direito. Abraço!
Acompanha aì os ùltimos vìdeos. Estamos fazendo um platformer usando as receitas do meu ùltimo livro! Que contèm todo còdigo prontinho pra copiar e colar!
outra ideia: cada tutorial com um link ou comentário contendo o codigo completo em formato texto. Porque olhando os videos, a gente tenta copiar mas se errar uma vírgula, quebra tudo! A maior parte do tempo é pausando e tentando copiar sem errar nada... Sem falar que as letras do godot são minúsculas, quem tem vista fraca, ou a internet lenta demais pra ver em alta definição, já era.
Oi tu conseguiria ensinar a fazer um sistema de dialogo em que ao interagir com o npc ocorre um dialogo com opções que você pode escolher qual resposta escolher, espero que esteja tudo bem em eu falar português aqui nos comentários
Yeah, well...momemtum is exactly what breaks slope movement, so snapping to slopes is breaking momentum. So for that kind of physics you would need another solution in fact.
The major "problem" is that it works😅 It snaps the character to the floor, so no force applied in the opposite direction will move it away from the floor, including a jump impulse. What you have to do is to disable the snap vector. Here, I have a tutorial about that! pigdev.itch.io/experiments/devlog/164517/jump-with-snap
@@pigdev NVM. Found a solution. The value that the Vector2.Down multiplies by seems to be what's causing it. So simply just lower the value to below 10 *(preferably 1)* when you need to leave the ground and then switch it back again when you need to land.
@@pigdev Deixa quieto. É que eu queria que o meu personagem ao pular encostasse num outro, que estaria em pé no chão, durante a descida sem que oferecesse resistência devido ao impulso, mas deve ser só cabacice minha na hora de anular a força ao encostar, rs. Grato pela resposta e pelo vídeo.
thanks but how to jump while moving a slope ? I set snap_vector to Vector2.ZERO to jump but it only works when I'm on flat ground or not moving on a slope for about 0.5 to 1sec
@@pigdev Ok I managed to fix it it was something else but there was another problem, the character doesn't stop instantly, it slides a bit down the slope and then stops, the higher the slope angle the farther it will slide down do you have any idea why ? This problem doesn't come from the floor angle since I set the max angle to 90 just in case. I can take video if you want, also thanks a lot for your help
You can check for the collision normal and change the sprite/animation accordingly. Search for KinematicCollision in the docs and you will understand :D
Yes, KinematicBody 3D also has the methods mentioned in the video, I didn't test yet, but it potentially behaves in the same way, so the solution presented here will probably work as well
Usted podría ganar mucho dinero poniendo en venta su conocimiento en las plataformas de Udemy y Domestika :) después de todo You Tube no te va a pagar nada, como mucho obtendrás 2 miseros USD por 10.000 visitas de la monetización, lo único que quiere You Tube es que tú hagas más vídeos, mientras ellos se hacen más ricos (a costilla de tus conocimientos, de tu tiempo de vida, coste de electricidad y edición de vídeos). S2.
It's on the roadmap! I'm just...kinda slow to set up stuff. But my next project is a course about Android monetization. I'll jump into it right after delivering my latrst ebook
This is a lot easier now in Godot4. Just turn on "Constant Speed" and adjust your "Snap length", I found 10px to work well for my character.
Thanks mate.
thanks for the tip
Dude you saved me a whole night of shooting raycasts in the dark. Reddit pointed me here and you did indeed explain it better than the docs, kudos 👍
I just got started with Godot recently and I've spent the last 3 days in a state of frustration for not being able to get my character to play nice with slopes. Other tutorials I tried all failed, I read the documentation for move_and_slide_with_snap over and over again - couldn't figure it out. Thanks for this video, if it wasn't for you I wouldn't have ever thought of using move_and_slide_with_snap only on the y component of velocity. Frankly, I still don't understand why that still works at all, but I'm not about to question it. Great stuff, good vibes, definitely subscribed, thanks a million Mr. Pigdev
I'm really glad to read that! Hope you find more useful content
"floor max angle" makes perfect sense though.
It defines the maximum angle of what's considered to be a floor by move_and_slide.
Anything steeper is considered a wall.
4:38 this AAAAAAAAAAAAA is perfect
I could not for the life of me figure out snapping to slopes. Thanks so much, youre a life saver!
thank u brozzer this was great, dont think we dont triple appreciate you teaching us in your second language ;)
I'm really glad you liked. I'm always happy to help!
MY GOODNESS! THANK YOU SO MUCH!! I've been finding a way for that slide to stop!! and all it takes was ", true".
I'm so glad it helped you!
Yes, thanks man! I was looking for an explanation like this for a long time. Greetings from the Netherlands!~
In case anyone is having trouble jumping, I had to set the snap vector to zero beforehand. Something like:
snap_vector = SNAP_DIRECTION * SNAP_LENGTH
if Input.is_action_just_pressed("jump") and is_on_floor():
snap_vector = Vector2.ZERO
is_jumping = true
Here's a post I've made to cover this :)
pigdev.itch.io/experiments/devlog/164517/jump-with-snap
Cara adoro seus tutoriais, principalmente porque você representa a gente na gringa, mostrando que nós também manjamos dos paranauê kkkk !
Keep doing what you're doing right now man ! You're helping me a lot !
UGH FINALLY! Thanks to you I finally figured out move and slide with snap.
Niiiice! Thanks for commenting this out! I'm glad to know it helped!
Thank you! This is absolutely helpful! Best explanation I've found on RUclips so far!
Great it helped! Really rewarding to know the video was useful.
Thank you for making this video! It really helped to figure out those pesky slopes.
They are tricky, aren't they :D
it works!... only if you no are working with jumping mechanics
Take a look at this pigdev.itch.io/experiments/devlog/164517/jump-with-snap
@@pigdev thanks!
@@pigdev Thank you so much!! D,:
Oh my god how have I just discovered your channel now this is so great! It helped me a whole lot
Glad it helped! Welcome to the channel
While this is a helpful video, I'd urge everyone to be careful with how they implement velocity. In this tutorial, it seems to me that the character ends up running much faster up the slope than on flat ground. This happens when the X Speed is preserved regardless of the movement angle. For more natural slope movement, it's better to preserve the overall velocity. This isn't a rule by any means, but it's good to know so that you can be more intentional with how you code your movement.
Working with radians is easy: Every value you want is simply some fraction of TAU.
As a baseline, TAU itself is equal to 360°, so just pretend that every mathematical operation you apply to TAU is being applied to 360 to figure out what it would look like in degrees.
3 * TAU / 4 == 270°
TAU / 2 == 180°
TAU / 4 == 90°
TAU / 6 == 60°
TAU / 8 == 45°
TAU / 16 == 22.5°
TAU / 24 == 15°
Any simple math using only constant numbers like this in any const definition will be precompiled into the script to become a proper floating number, and not take any processing time while your game is running. The "deg2rad" function you use simply does something like "deg * TAU / 360" to return some fraction of TAU.
So so basically...45*(360/360)?
What's the advantage of that, apart from the floaring numbers compilation you've mentioned?
I mean, in run time it can't pre compile.
@@pigdev TAU is actually 2 * PI, so 1 TAU is 360 degrees, but in radians (6.2831853071...), not literally 360.
So the math here is really more like "(45.0 / 360.0) * TAU" for "45 out of 360 turned into radians", but I changed the order of operations because I am an old school C programmer who is used to working with integer math and fixed-point operations, eg. so you have to multiply before you divide or else you would lose precision. :P
If you use "deg2rad(45)" in a const, I think it would be the same thing as "45.0 / 360.0 * TAU" anyway, and maybe optimized,
but the PURPOSE is that I like the look of "TAU / 8" more because it directly and plainly means "1/8th of a circle" instead of some number "45", and the math is simple enough to be readable.
@@JessieEchidna ohh, I find it harder to get stuff like...48 degrees or these kind of specifc values. But I think I got the idea, for some it is easier to think of, e.g. TAU/4, I think that it can be useful for writing things in term of circles. E.g. 2*TAU is easier to write and understand that it is 2 spins than 720 degrees
Ohhh my god, you saved my life, thank u so much
Thank you so much for watching!! I'm glad it was useful!
Thanks man! you're a legend and happy 5k subs!
Thanks! And thank you for being part of this 🐷👌
You're the best! Thanks! Keep it up!
0:12
"STOP!"
Okay, sorry, I'll see myself out
NOOOOO 😭😭
Floor max angel mean there lass then this angel is considered as floor for the phisics and above this as a slope
Thank you very much.
Thank you for watching!
hey so, while the code works almost as intended, i seem to have problems jumping up slopes, is there a way to fix this?
Yep. Take a look at that:
pigdev.itch.io/experiments/devlog/164517/jump-with-snap
@@pigdev i appreciate the help! but it seems like it only works when the players jump height is too high
@Team Necho then it seems you are either using a gravity too heavy, or your snap_vector is too big.
@@pigdev it works now, thank you!
I LOVE BACON
Ahhh! So the trick is updating the vertical parameter of Velocity only! God, I'm suffering with slopes for months!
If you don't mind, I didn't really understand why that solves the problem here. Could you elaborate more?
Also, does it work when you walk across (downward or upward) tiles with different inclinations? (Like terrain from Megaman Zero, where steepness can change across the same floor/tile segment) And have you tested it with curved terrain like loops or semi loops?
And finally if I may ask: the "velocity.Y = move_and_slide().Y" trick works on Godot 4.0 too?
Thanks so much for making this tutorial!
Thank you so much for watching!
So you wanna tell me that I spent more than 30 hours in unity to get the movement kind of working and godot has it basically built in!? I am so switching to godot. Thanks for the video!
So...kinda yeah...I mean...yeah. come to Godot already 😅
For some time, I wanted to know how to walk a loop in godot (like sonic)
I think you can change the floor normal and the snap normal to snap the character to the loop you can basically take the collision normal and use it as the floor normal and invert it to use as the snap normal
If I remember correctly someone made a sonic engine in Godot but it's a bit messy 🤔
Hi Pigdev, what if i want the character to go down the slope like the angle in ur video thumbnail? i dunno how to make the character slide down with its position parallel to the slope.
Hey! Follow me on twitter heh, I've made a small written tutorial explaining that in my experiments project. Check it out:
pigdev.itch.io/experiments/devlog/158787/tilting-on-slopes
@@pigdev Waaah! Thank you so much Pigdev! Yes ill follow u on twitter and on itch as well. Thank you!! :)
Hey Pigdev, do you know how ''slopes'' are handled in stuff like old top-down Zelda? It seems like different places can have different simulated Z values, leading arrows and even the more complex arcing bombs etc. to collide or pass when shot/thrown, but these little transitions acting as abstractions of slopes where you simply walk or shoot straight projectiles between different heights as if nothing changed make me feel Z differences are calculated based on obstacles that have nothing to do with the then presumably singular ground layer. (Those bombs might even add x/y if z destination is lower and vice versa, idk)
would you be able to make a 3d tutorial for this?
I've been trying to make a 3d kinematic player but I can't seem to get the move_and_slide_with_snap() func to work as it does in your video.
Currently I have to give up because I'm still too much of a newb to figure out if my code is just broken or if v3.4 actually has bugs
There's another option to stop sliding down while standing: just stop applying gravity while grounded
Smart 🤔
I also thought of that before and tried to set gravity = 0 (instead of maybe using false or something)...and my character just floated up and did not stop :') I'm sure I was just missing something, but it was funny to watch!
thank you =)
Thank you! 😊
Poderia criar curso na udemy, faria sucesso, pois voce tem uma didática boa, e conteudo revelevantes!! parabens piggy
E se eu te disser que esse ano sai curso no Udemy e várias aulas no Skillshare? 👀
@@pigdev onde compro early access?! Hahaha massa
@@pigdev Que massa, já vou deixar a grana separada
Cara, parabéns e obrigado pelo ótimo trabalho. Venho pedir que vc faça um tutorial completo de plataforma 2d. Pois eu estava seguindo o curso do BornCG, é muito bom, tudo funcionando, mas ele não ensina combate, nem slope, nem como botar online multiplayer, nem dash etc. E toda vez que eu tento implementar codigos de outros tutoriais NÃO FUNCIONA. Eu tentei usar o teu codigo, mas no meu já tá com um monte de finite states, muita coisa interligada, então não funciona. Um curso completo ainda não existe, então poderia fazer muito sucesso, pois a maioria dos professores em inglês fala muito rápido e as pessoas de outros países não entendem direito. Abraço!
Acompanha aì os ùltimos vìdeos. Estamos fazendo um platformer usando as receitas do meu ùltimo livro! Que contèm todo còdigo prontinho pra copiar e colar!
@@pigdev SIm, parabens pela iniciativa! Eu deixei um comentario no video Platformer Essentials, vê lá! abraço
outra ideia: cada tutorial com um link ou comentário contendo o codigo completo em formato texto. Porque olhando os videos, a gente tenta copiar mas se errar uma vírgula, quebra tudo! A maior parte do tempo é pausando e tentando copiar sem errar nada... Sem falar que as letras do godot são minúsculas, quem tem vista fraca, ou a internet lenta demais pra ver em alta definição, já era.
Oi tu conseguiria ensinar a fazer um sistema de dialogo em que ao interagir com o npc ocorre um dialogo com opções que você pode escolher qual resposta escolher, espero que esteja tudo bem em eu falar português aqui nos comentários
But this doesn't work with physics that have momentum or low friction (when you stop on a slope it still slides down a little bit)
Yeah, well...momemtum is exactly what breaks slope movement, so snapping to slopes is breaking momentum. So for that kind of physics you would need another solution in fact.
idk, have some cake ?
The function seems to cause a lot of problem when trying to jump. Is there any work around this issue?
The major "problem" is that it works😅
It snaps the character to the floor, so no force applied in the opposite direction will move it away from the floor, including a jump impulse.
What you have to do is to disable the snap vector. Here, I have a tutorial about that!
pigdev.itch.io/experiments/devlog/164517/jump-with-snap
@@pigdev NVM. Found a solution.
The value that the Vector2.Down multiplies by seems to be what's causing it. So simply just lower the value to below 10 *(preferably 1)* when you need to leave the ground and then switch it back again when you need to land.
hi, if I want to do that method in a player who had a state machine nodes, how i need to implement that in the player?
Hmm, hard to tell without the context of how this states and transitions were implemented 😬
@@pigdev
:(
is like idenpendecy injection,
i followed this tutorial right here:
ruclips.net/video/DPxIMVC0oZA/видео.html
@@pigdev Hi, i already fixed, thanks anyways you helped me so much (in the video)
Como faço pra escorregar sem nenhuma resistência na descida? Até agora não achei nenhuma solução pra isso.
Só usar o move_and_slide e passar false no argumento "stop_on_slopes", no vídeo mostra isso.
@@pigdev Deixa quieto. É que eu queria que o meu personagem ao pular encostasse num outro, que estaria em pé no chão, durante a descida sem que oferecesse resistência devido ao impulso, mas deve ser só cabacice minha na hora de anular a força ao encostar, rs. Grato pela resposta e pelo vídeo.
Thank you!!! Sheesh
Thank YOU for watching!
thanks but how to jump while moving a slope ? I set snap_vector to Vector2.ZERO to jump but it only works when I'm on flat ground or not moving on a slope for about 0.5 to 1sec
Remember to set it back when the character is on the floor again.
if is_on_floor:
snap_vector = SNAP_DIRECTION * SNAP_LENGTH
ruclips.net/video/9l-tf97z2bg/видео.html
@@pigdev Ok I managed to fix it it was something else but there was another problem, the character doesn't stop instantly, it slides a bit down the slope and then stops, the higher the slope angle the farther it will slide down do you have any idea why ? This problem doesn't come from the floor angle since I set the max angle to 90 just in case.
I can take video if you want, also thanks a lot for your help
The above problem came from absurdly high gravity, to fix it you need disable or lower gravity while on floor, thanks @Pigdev for helping me out
How to make another pose on slopes?
You can check for the collision normal and change the sprite/animation accordingly.
Search for KinematicCollision in the docs and you will understand :D
Obrigado!
help, my player is jumping after climbing a slope and falling later, i cant explain it so good sorry.
Try to play with snap!
@@pigdev thx, but I already fixed the bug (a great time ago)
can this solution be used to fix this?
watch?v=NSNe91lMe_Q
or it just works for 3D?
Yes, KinematicBody 3D also has the methods mentioned in the video, I didn't test yet, but it potentially behaves in the same way, so the solution presented here will probably work as well
Usted podría ganar mucho dinero poniendo en venta su conocimiento en las plataformas de Udemy y Domestika :) después de todo You Tube no te va a pagar nada, como mucho obtendrás 2 miseros USD por 10.000 visitas de la monetización, lo único que quiere You Tube es que tú hagas más vídeos, mientras ellos se hacen más ricos (a costilla de tus conocimientos, de tu tiempo de vida, coste de electricidad y edición de vídeos). S2.
It's on the roadmap! I'm just...kinda slow to set up stuff. But my next project is a course about Android monetization. I'll jump into it right after delivering my latrst ebook
Brasileiro?
Todo dia...todo dia eu acordo e ainda sou brasileiro. Não to tankando mais, sério mesmo kkkkkkk
Respondendo, sim. Brasileiro. 🐷🇧🇷
thank you :D
Thank YOU for watching :D