How to simplify this function?

I have this function that has 2 if paths that lead to a jump. The blocks of code are exactly the same, which annoys me to no end.

If possible, I’d rather not use another function, but if I have to I will…

Here is the func:

func vault_jump(delta:float):
	#Detection
	if Input.is_action_just_pressed("jump"):
		jump_buff = get_tree().create_timer(jump_vault_buff_amount)

	if jump_buff.time_left > 0:
		#Vaulting
		if vault_cast.is_colliding():
			var vault_normal := vault_cast.get_collision_normal(0)
			if vault_normal.dot(Vector3.UP) > 0:
				#Do the vault
				pass

			#Jump If Shapecast Is False Detecting
			elif is_on_floor():
				#This is a jump
				pass
		#Jumping
		elif is_on_floor() or (coyote and coyote_timer.time_left > 0):
			#This is also a jump
			pass

You can return early from the vault scenario, then you don’t need any of that first jumping code, because it’s covered by the second jump code. I haven’t tested this code, I’m on mobile, so let me know if you have any issue with this code.

func vault_jump(delta:float):
	#Detection
	if Input.is_action_just_pressed("jump"):
		jump_buff = get_tree().create_timer(jump_vault_buff_amount)

	if jump_buff.time_left > 0:
		#Vaulting
		if vault_cast.is_colliding():
			var vault_normal := vault_cast.get_collision_normal(0)
			if vault_normal.dot(Vector3.UP) > 0:
				#Do the vault
				return

		#Jumping
		if is_on_floor() or (coyote and coyote_timer.time_left > 0):
			#This is also a jump
			pass

It works!

But, just to make sure I understand it, the return basically cancels every under it including the jump if statement?

More or less yes.
return will exit the whole function immediately, so whatever comes after that will not be processed.

2 Likes

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