Im working on a character controller that works similarly to sonic the hedgehog from his debut.
Here is the code:
extends CharacterBody2D
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
@onready var animated_sprite = $AnimatedSprite2D
func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y += gravity * delta
# HHandle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("move_left", "move_right")
# Flip the Sprite
if direction > 0:
animated_sprite.flip_h = false
elif direction < 0:
animated_sprite.flip_h = true
if is_on_floor():
if direction == 0:
animated_sprite.play("idle")
else:
animated_sprite.play("Walk_run")
else:
animated_sprite.play("fall")
if direction:
velocity.x = direction * SPEED
else:
var des_rate = SPEED * 0.1
velocity.x = move_toward(velocity.x, 0, des_rate)
move_and_slide()
Im trying to add acceleration and have no idea how to do it. Can someone help?
In your code, you add speed to the player by assigning a value to the velocity, which means that you always give the player the same velocity (i.e. same speed).
However if you keep adding up, the speed can increase too much, which is why people usually put a max speed so that the game is still playable.
I would rewrite your code like this:
extends CharacterBody2D
const MAX_SPEED = ...
const JUMP_VELOCITY = -400.0
const ACCELERATION = ...
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
@onready var animated_sprite = $AnimatedSprite2D
func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y += gravity * delta
# HHandle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("move_left", "move_right")
# Flip the Sprite
if direction > 0:
animated_sprite.flip_h = false
elif direction < 0:
animated_sprite.flip_h = true
if is_on_floor():
if direction == 0:
animated_sprite.play("idle")
else:
animated_sprite.play("Walk_run")
else:
animated_sprite.play("fall")
if direction:
velocity.x += direction * ACCELERATION
else:
var des_rate = SPEED * 0.1
velocity.x = move_toward(velocity.x, 0, des_rate)
velocity.x = clamp(velocity.x, -MAX_SPEED, MAX_SPEED)
move_and_slide()