Loading...
Loading...
Code smooth character movement with gravity, jumping, and collision detection for a 2D platformer.
Create a new scene with 'CharacterBody2D' as the root node. Rename it to 'Player'. Add a 'Sprite2D' child node and assign your character texture. Add a 'CollisionShape2D' child and create a rectangle or capsule shape that fits your sprite. This setup provides the physics body for your character.
Attach a script to the Player node. In the _physics_process function, create a variable for velocity: `var velocity = Vector2.ZERO`. Get the input direction: `var direction = Input.get_axis('ui_left', 'ui_right')`. This captures left/right arrow or A/D key presses.
Apply movement logic: If direction is not zero, set `velocity.x = direction * speed` (where speed is a variable you define, e.g., 300). If direction is zero, apply friction: `velocity.x = move_toward(velocity.x, 0, speed)`. This creates smooth acceleration and deceleration.
Add gravity: In _physics_process, before movement, add `if not is_on_floor(): velocity.y += gravity * get_physics_process_delta_time()`. Define gravity as a variable (e.g., 980). This makes the player fall when not on the ground.
Implement jumping: Check for jump input with `if Input.is_action_just_pressed('ui_jump') and is_on_floor(): velocity.y = -jump_velocity`. Define jump_velocity (e.g., -400 for upward force). The is_on_floor() check ensures the player can only jump when standing on something.
Finally, apply the velocity: `move_and_slide()`. This built-in Godot function handles collision detection and response automatically. Test your game with F5 and adjust speed, gravity, and jump values until the movement feels right.