How to Move a Character in Godot 4 with GDScript

2026-12-02来源 dev.toEnglish
How to Move a Character in Godot 4 with GDScript

Originally published on CodingCush.

You move a character in Godot 4 by giving it a CharacterBody2D node and a short GDScript that reads the keys every physics frame and calls move_and_slide(). That is the whole trick, and the script is only eight lines long. The rest of this post answers the five questions that trip up nearly every beginner: which node to use, where the code goes, how Godot reads the keyboard, why characters walk through walls, and how the same code turns into a platformer. Everything here targets Godot 4.3, and every line of code was run first. If you prefer to watch the lesson first, the video version sits in the Godot 4 Full Course in Hindi, free on YouTube.

Question 1: which node should the player be?

Godot gives you several nodes that can move. A plain Node2D has no collision, so your character would glide through every wall. An Area2D can detect overlaps, but it cannot push back against a wall. A CharacterBody2D is built for this job: it detects collisions when it moves, and your code decides what happens next.

Make a new scene and add a CharacterBody2D as the root. Name it Player. Then give it two children. A Sprite2D shows the character on screen, and a CollisionShape2D gives it a solid body the physics engine can bump into. For the shape, pick a RectangleShape2D sized to cover the sprite. If you have no sprite yet, our Snake game art pack has a ready-made set you can drop straight in.

One setting matters first. In the Inspector, find Motion Mode on the CharacterBody2D. The default is Grounded, right for a platformer. For a top-down game, set it to Floating, which tells Godot every collision is a wall.

Question 2: where does the movement code live?

Attach a script to the Player node and write this:

extends CharacterBody2D @export var speed = 300.0 func _physics_process(_delta): var direction = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down") velocity = direction * speed move_and_slide() 

Three lines do the work. Input.get_vector reads the four arrow keys and returns a direction, like (1, 0) for right or (0, -1) for up. Multiplying by speed turns it into a velocity in pixels per second, so 300 means the character crosses 300 pixels in one second. Then move_and_slide() moves the body and slides it along anything it hits, instead of stopping dead.

Notice the function name: _physics_process, not _process. Godot calls _physics_process 60 times a second by default, while _process runs once per rendered frame, which changes with the frame rate. Movement belongs in _physics_process because physics needs a steady beat. Code in _process still moves the character, but the speed changes whenever the frame rate does.

The Godot 4 script editor showing player.gd, the movement script from this tutorial, with extends CharacterBody2D, an exported speed of 300.0, and _physics_process calling Input.get_vector and move_and_slide

The movement script open in the Godot 4 script editor. Eight lines, and the player already walks.

Question 3: how does Godot read the arrow keys?

The ui_left, ui_right, ui_up and ui_down names in the script are input actions, and they already exist. Every Godot project ships with built-in ui_ actions, and the arrow keys are wired to them by default. That is why the script works with no setup: press an arrow key, and Input.get_vector returns the matching direction.

Input.get_vector takes four action names in this order: left, right, up, down. It returns a Vector2, and it normalises the result, so pressing up and right together gives a diagonal of length 1, not 1.41. Your character moves at the same speed in every direction.

For your own keys, open Project, then Project Settings, then the Input Map tab, and add an action. Name it move_left, click the plus button, and press the key you want. Then swap the names in the script. The rest stays the same: the script talks about what the player wants, and the Input Map decides which key means it.

Question 4: why does my character walk through walls?

Three ways to move a body exist, and only two respect walls:

Method What it does When to use it
move_and_slide() Moves the body and slides it along anything it hits Players, enemies, anything that walks around
move_and_collide() Moves the body and stops at the first thing it hits Bullets, or when you want to code the bounce yourself
position += velocity * delta Teleports the body a little each frame Never for a physics body; it skips collision checks

Setting position directly is the usual culprit. It looks like it works, because the sprite moves, but the physics engine never gets a say. The body jumps from one spot to the next without checking what stands between them, so thin walls get skipped. The official CharacterBody2D documentation says the same in its first section: do not set position directly, use move_and_collide or move_and_slide instead.

A wall needs the same two parts: a StaticBody2D with a CollisionShape2D, the same way you built the player. A sprite alone is only a picture; without the body and its shape, the wall is decoration and the player walks straight past it. The floor works the same way, with a wide rectangle along the bottom of the screen.

Question 5: can the same script run a platformer?

Yes, with two changes: gravity and a jump. A platformer moves left and right, and falls the rest of the time:

extends CharacterBody2D var speed = 300.0 var jump_speed = -400.0 func _physics_process(delta): velocity += get_gravity() * delta if Input.is_action_just_pressed("ui_accept") and is_on_floor(): velocity.y = jump_speed var direction = Input.get_axis("ui_left", "ui_right") velocity.x = direction * speed move_and_slide() 

Gravity comes from get_gravity(), which returns the value in Project Settings, 980 pixels per second squared by default. Adding it to velocity every frame makes the character fall faster the longer it is in the air, which is how a jump gets its arc. The jump line fires only when two things are true at once: the player just pressed the key, and is_on_floor() says the body is standing on something. Without that check, the player could jump again in mid-air, forever.

Two details are easy to miss. First, jump_speed is negative because in Godot, up is negative Y, so -400 pushes the character up. Second, the key here is ui_accept, the built-in action bound to Space and Enter, so this version also runs with no Input Map setup. If you want a full game built on these ideas, the official Your first 2D game tutorial in the Godot docs builds a small dodge-the-enemies game step by step.

Five mistakes that stop a character moving

Most broken movement comes from one of five small slips. First, the script is attached to the wrong node, usually the Sprite2D instead of the CharacterBody2D, so move_and_slide runs on a node that has no velocity. Second, the CollisionShape2D has no shape assigned, so the body has nothing to collide with. Third, the code sits in _process instead of _physics_process, and the character stutters or runs at a different speed on every machine. Fourth, the script sets position directly, which looks fine in an empty room and breaks the moment a wall appears. Fifth, an input action name is typed wrong, so get_vector quietly returns (0, 0). When nothing moves at all, check those five in order before rewriting anything.

Frequently asked questions

Do I need to create input actions before this works?

No. The ui_left, ui_right, ui_up and ui_down actions are built into every project, and the arrow keys are already bound to them. Create your own only when you want different keys, like WASD, or a gamepad.

What speed should I use?

Start at 300. It is fast enough to feel responsive and slow enough to control in a 640 by 360 viewport. Small rooms want 200, open maps can take 400. The @export in front of speed puts a slider in the Inspector, so you can tune it while the game runs.

Why is my character faster when moving diagonally?

It should not be, if you use Input.get_vector, because the function normalises the direction. If you read the keys separately and add the directions yourself, the diagonal becomes about 1.41, so normalise it with direction.normalized() or switch to get_vector.

Does this work in 3D too?

The idea is the same, but the node is CharacterBody3D and the direction is a Vector3. The official docs cover both on the same CharacterBody2D/3D page, and the pattern is identical: read input, set velocity, call move_and_slide.

What to build next

You now have a character that walks, slides along walls, and jumps. Give it something to do. Add a second wall and a gap to jump over, then swap the plain square sprite for a real character from our free Catch the Fruit art pack. If you get stuck, the video version of this lesson is in the Godot 4 Full Course in Hindi, free on YouTube, and every episode is listed on our Godot 4 Hindi course page. Next lesson, we will give this character an animation, so it walks instead of glides.

原文:https://www.a8q9.cn/en/article/how-to-move-a-character-in-godot-4-with-gdscript-b33207.html

相关文章