J
J.Dot

Questions about code from the Make a Platformer tutorial.

Here is the code from the create platformer tutorial. I am confused about 2 different things. Ouchiespot is the name of the area2d node.

func _on_OuchieSpot_body_entered(body: Node) -> void:

  if body.global_position.y > get_node("OuchieSpot").global_position.y:
        return
  queue_free()

1.This code is saying that if kinematic2d body has a y value greater than the enemy area2d y value to stop code there (return) else execute queue free? Should it not be the opposite? If the player y value is less than area2d return, otherwise queue_free?

2. Initially the destroy part of the code did not work and I could not find out why. I had the queue_free part of the code at the same indentation level as the return and just so happened to re align it with the if and the code worked!? Why would the indentation be a issue? It did not throw any errors either.




  • Nathan Lovato replied

    1.This code is saying that if kinematic2d body has a y value greater than the enemy area2d y value to stop code there (return) else execute queue free? Should it not be the opposite?

    The code is correct. We are trying to check if we are hitting the collider from below, in which case we did not fall on the enemy, but we are most likely currently jumping and touching the enemy's hitbox coming from below. If so, the jump shouldn't kill the enemy.

    Why would the indentation be a issue?

    Indentation controls what code block an instruction is part of. If you write the following code:

    func _on_OuchieSpot_body_entered(body: Node) -> void:
      if body.global_position.y > get_node("OuchieSpot").global_position.y:
            return
            queue_free()

    Then the line queue_free() is never called. Why? Because it's part of the conditional block. If the condition is true, the computer executes the return command, ending the function's execution and ignoring the call to queue_free(). Ideally, there should probably be a warning somewhere that this line of code can never be run.