Skip to content

Code comments

Mex777 edited this page Jun 4, 2024 · 1 revision

GDScript Code Comments Best Practices

1. Comments Should Enhance Understanding

Comments serve as supplementary information to the code. They should clarify intent, assumptions, or complex logic. Avoid redundant comments that merely restate what the code already expresses.

2. Prioritize Clear Code Over Comments

Strive for self-explanatory code. Well-named variables, functions, and classes reduce the need for excessive comments. If the code is unclear, consider refactoring it.

3. Explain Why, Not What

Instead of describing what the code does (which is evident from the code itself), focus on explaining why certain decisions were made. Share context, constraints, or design rationale.

6. Avoid Obvious Comments

Comments like “Increment the score” for score += 1 are unnecessary. Reserve comments for non-obvious or context-specific details.

7. Review and Maintain Comments Regularly

As code evolves, revisit comments. Remove outdated ones and ensure they remain accurate.

Remember, thoughtful comments enhance collaboration and make your codebase more accessible to others. Happy coding! 🚀🎮

Examples:

# Function for updating the animation based on the character's state.
func update_animation() -> void:
	if attacking:
		return
	if velocity.x != 0:
		animation.play("Run" + Player.get_skin())	
	else:
		animation.play("Idle" + Player.get_skin())
		
	if velocity.y < 0:
		animation.play("Up" + Player.get_skin())
	if velocity.y > 0:
		animation.play("Down" + Player.get_skin())


# Function for handling damage taken by the character.
func take_damage(damage: int) -> void:
	if not Game.in_god_mode():
		Player.take_damage(damage)
	
	# Flash the sprite red when taking damage.
	$Sprite.modulate = Color.RED
	await get_tree().create_timer(0.1).timeout
	$Sprite.modulate = Color.WHITE