MoveAndSlide() Doesn't work!

Godot Version

Godot: 4.2.1

Question

I’m new to Godot and I just started learning C#. I made a basic movement script for a 2d player but there is an issue with MoveAndSlide(). This is the script:

using Godot;
using System;

public partial class PlayerMovementScript : CharacterBody2D
{
	// Declaring velocity outside of _Process to retain its value between frames
	private Vector2 velocity = new Vector2();

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		// Reset velocity to zero at the start of each frame
		velocity = Vector2.Zero;

		if (Input.IsActionPressed("ui_left"))
		{
			velocity.X -= 50;
		}

		if (Input.IsActionPressed("ui_right"))
		{
			velocity.Y += 50;
		}

		// Move and slide with the calculated velocity
		MoveAndSlide(velocity, Vector2.Up);


	}
}

Error Code

**> **
> CS1501: No overload for method ‘MoveAndSlide’ takes 2 arguments C:\Users\Danilo Denic\Documents\Mountainus\Scripts\PlayerMovmentScript.cs(31,3)

You probably seeing some old tutorial because in godot 4 MoveAndSlide don’t take any argument, also you’re creating a velocity variable that also is wrong because CharacterBody2D already has a variable called velocity and make use of that. I recommend you read the updated godot documentation:

Using CharacterBody2D/3D — Godot Engine (stable) documentation in English

4 Likes

Also you should do that code inside _PhysicsProcess callback, everything physics related should be done in _PhysicsProcess callback

3 Likes

I fixed it

using Godot;
using System;

public partial class PlayerMovement : CharacterBody2D
{
	public float moveSpeed = 150.0f;
	public float jumpVelocity = 400.0f;
	public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();

	public override void _Ready()
	{
	}

	public override void _PhysicsProcess(double delta)
	{
		Vector2 velocity = Velocity;

		// Apply gravity if in air
		if (!IsOnFloor())
		{
			velocity.Y += gravity * (float)delta;
		}

		Velocity = velocity;
		MoveAndSlide();
	}
}

1 Like