I remade my code for make the character slower when touched it still doesnt work

Godot Version

i remade my code fr make the character slower when he touches it . it still doesnt work. in reality nothing happens

Question

Ask your question here! Try to give as many details as possible.

If you share code, please wrap it inside three backticks or replace the code in the next block:

extends Area2D

var slow_speed = 150
var normal_speed = 300 
var speed = 300
func _on_body_entered(body):
	# Ensure only the player/character is affected
	if body.is_in_group("player"): 
		body.velocity.x = slow_speed

func _on_body_exited(body):
	if body.is_in_group("player"):
		body.velocity.x = normal_speed

Add print() statements to check if this code is being triggered at all, or not.

Also, please share the code of the Player node.

2 Likes

i made the print part and yes its actrually being triggered. But its still does nothing to the character speed

and this is the players code

extends CharacterBody2D

var SPEED = 300.0
var JUMP_VELOCITY = -400.0

func _physics_process(delta: float) → void:

Add the gravity.

if not is_on_floor():
velocity += get_gravity() * delta

# Handle jump.
if Input.is_action_just_pressed("ui_accept") 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("ui_left", "ui_right")

$Sprite2D.flip_h = int(direction - 1)

$Sprite2D.flip_h = int(direction + 1)

if direction:
	velocity.x = direction * SPEED
else:
	velocity.x = move_toward(velocity.x, 0, SPEED)
	
move_and_slide()

func set_speed(new_speed: float):
SPEED = new_speed

You are setting velocity.x to a new value before move_and_slide(), replacing the value set from the area. The area shouldn’t change velocity.x, but the player’s SPEED instead.

Additional note: Since SPEED is declared as a variable, its name should be in snake_case (speed) and not CONSTANT_CASE (which is for constants). Same goes for JUMP_VELOCITY.

1 Like

what is a “snake_case” and what is ther difference to the const

snake_case is a naming convention where letters are all lower case. In GDScript, this should be used for variables.
For constants it’s the opposite, capital letters only.

Following the naming conventions makes it easier for yourself and others to read your code.

so i just changed the script and sitill nothing happens.

extends Area2D

var slow_speed = 300.0
var normal_speed = 300.0
var speed = normal_speed
func _on_body_entered(body):

Ensure only the player/character is affected

if body.is_in_group(“player”):
body.speed = slow_speed
print(“slow_down”)

func _on_body_exited(body):
if body.is_in_group(“player”):
body.speed = normal_speed
print(“back_to_normal”)

slow_speed and normal_speed have the same value.

i9 changed the values and it worked now. Thanks.