I’m just trying to get the basics of movement down for a side scrolling 2D platformer when I got stuck on coding the jumping. I can’t seem to understand on how to get it to work. I tried watching tutorials to get close, but now my character only does a short hop. Here is my code, if I’m missing something then please let me know.
using Godot;
using System;
using System.Security.Cryptography.X509Certificates;
public partial class player : CharacterBody2D
{
[Signal]
public delegate void HitEventHandler();
Here’s a couple of things I’m noticing when looking at your script.
Defining a pre-existing variable
The variable velocity, which is used in conjunction with MoveAndSlide(), is inherited from the CharacterBody2D class (see class reference). There’s no need to define it manually. Doing so only sows confusion as to which variable is in use: the local, or the inherited variable. While it may still be working, it’s a redundant variable.
Incorrect use of the velocity variable
The velocity variable represents the current velocity of the object and can be modified to achieve custom movement behaviour (such as your script). This is usually done with MoveAndSlide() as it is a convenient way to perform character movement. Without it, you would have to perform your own collision force calculations - usually using MoveAndCollide() (see the manual).
While you are succesfully utilizing MoveAndSlide() to perform your movement, you are also manually performing your own integration:
Position += velocity * (float)delta;
You are essentially moving your character twice.
Not separating your velocity axes when processing the velocity
if (velocity.Length() > 0){
velocity = velocity.Normalized() * speed;
}
As we have just established, velocity is a direct representation of how fast your character is moving. Setting the length of your velocity in the way you’ve done in the above snippet does not take into account the character’s motion when in the air. When not grounded (!IsOnFloor()), the y-velocity of your character is affected by the normalization you’re performing. Furthermore, you likely don’t want your jump/fall speed to be affected by your speed. In general, separate your axes when processing movement.
The code above is likely what is messing with your jump.