Why am I flying?

4.5

(I was trying to make a state machine and learn about it)

so my idle state switches to move state if the player is moving, and it switches to jump state if jump is pressed. (the move state is almost the same.)

class_name Jump
extends State

@onready var anim: AnimationPlayer = get_parent().get_parent().find_child("AnimationPlayer")
@onready var player: CharacterBody2D = get_parent().get_parent()

func physics_uodate(_delta: float):
	if Input.is_action_just_released("jump"):
		if !player.direction:
			pstate_machine.transition_to("Idle")
		else:
			pstate_machine.transition_to("Move")
			
			
	if player.direction:
		player.move(90, 600, _delta)
		player.jump(-90)
	else:
		player.move(0, 600, _delta)
		player.jump(-90)

	player.move_and_slide()

(The if player.direction stuff on the bottom is for the player being able to move even while jumping.)

And when I long press I fly.

(And yes, I did add a if is_on_floor() then jump.)

Here’s the player code:

extends CharacterBody2D

var direction := Input.get_axis("left", "right")
@onready var anim: AnimationPlayer = $AnimationPlayer

func _physics_process(delta: float) -> void:
	direction = Input.get_axis("left", "right")
	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta
		

func move(speed: int, accel: float, delta: float):
	velocity.x = move_toward(velocity.x, direction * speed, accel * delta)
	
	# Handle jump
func jump(jump_height: int):
	velocity.y = jump_height

You spelled physics_update as physics_uodate. I’m not sure how this code is working at all TBH. However, ignoring that, you are calling jump() every physics frame. You should call it once when the jump button is pressed. Not every frame. That’s why you’re flying.

1 Like

Yeah I noticed that “uodate” typo in the state script.

Wait so even if I did this

	if Input.is_action_just_pressed("jump") and player.is_on_floor():
		pstate_machine.transition_to("Jump")

In the idle state script, the jump is still being called many times?

Yes.

Do this instead:

class_name Jump
extends State

@onready var anim: AnimationPlayer = get_parent().get_parent().find_child("AnimationPlayer")
@onready var player: CharacterBody2D = get_parent().get_parent()

func physics_uodate(_delta: float):
	if Input.is_action_just_released("jump"):
		if !player.direction:
			pstate_machine.transition_to("Idle")
		else:
			pstate_machine.transition_to("Move")
			
			
	if player.direction:
		player.move(90, 600, _delta)
#		player.jump(-90)
	else:
		player.move(0, 600, _delta)
#		player.jump(-90)

	player.move_and_slide()

Then:

	if Input.is_action_just_pressed("jump") and player.is_on_floor():
		player.jump(-90)
		pstate_machine.transition_to("Jump")

Obviously, if you’re in the player script, don’t reference player like I did.

1 Like

Thank you! :slightly_smiling_face:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.