Character doesn't move with MoveAndSlide() (C#)

Godot Version

v4.5.1.stable.mono.official [f62fdbde1]

Question

I am having trouble getting a simple enemy to move in my Godot 4 project using C#.
The sprite doesn’t move when I run the scene.
My scene structure is
Slime (CharacterBody2D)
├── AnimatedSprite2D
└── Killzone
└── CollisionShape2D

using Godot;
using System;

public partial class Slime : CharacterBody2D 
{
    [Export]
    public float speedSlime = 60f;
    
    public override void _PhysicsProcess(double delta)
    {
        // Setting velocity and using MoveAndSlide
        Velocity = new Vector2(speedSlime, 0);
        MoveAndSlide();
    }
}

Based on just the code alone, this should work as you’d expect.
The few things I can think of are:

Make sure the CollisionShape2D actually has a collision shape resource added to it

Make sure you compiled and saved the scene after you added the script to it, it’s not automatically saved if you just run the project from your IDE, you need to save it in godot first.

1 Like

The collisionShape2D has rectangle shape and its a child node of killzone.
└── Killzone
└── CollisionShape2D
I don’t know what compile is.
I guess its the build project thing? If so I did it before run the game.
Idk man, thank you for reply tho.

Print something in _PhysicsProcess() to check if it’s indeed running every frame.

1 Like

It’s a bit confusing that you use C# but you don’t know what compiling means.

2 Likes

Is the script attached to your character?

Is the speed in the inspector set to 0?

What does the killzone do?

The code looks fine. :thinking:

1 Like

I’d recommend switching to GDScript. Godot in C# has enough of a learning curve if you know C#.

Either way, go do this tutorial: Your first 2D game — Godot Engine (stable) documentation in English It’s got a C# and a GDScript version. The question you’re asking, and your follow-up lack of knowledge will be answered by following this.

1 Like

Yeah I’ll try gdscript thank you.

1 Like