### GDScript Function Definition and Usage Source: https://context7.com/context7/gdscript-tutorials/llms.txt Demonstrates how to define and use functions in GDScript, including functions with parameters, return types, and default values. It also shows example usage within the _ready and _process functions. ```gdscript func try_purchase(cost: int) -> bool: if score >= cost: score -= cost return true return false func _ready(): display_message("Game started!") var damage = calculate_damage(10, 1.5) print("Damage dealt: ", damage) var new_score = add_score(100) print("Current score: ", new_score) heal_player() # Uses default value heal_player(25.0) # Custom healing amount print("Player health: ", player_health) var success = try_purchase(50) print("Purchase successful: ", success) func _process(delta: float) -> void: # Called every frame with delta time update_game_state(delta) func update_game_state(delta: float) -> void: # Game logic here pass ``` -------------------------------- ### GDScript: Dictionary Usage for Game Data Source: https://context7.com/context7/gdscript-tutorials/llms.txt Illustrates creating, accessing, modifying, adding, checking for keys, getting values with defaults, checking multiple keys, removing key-value pairs, checking for emptiness, iterating over dictionaries, and handling nested dictionaries in GDScript. ```gdscript extends Node2D # Global game dictionary var game_data = {} func _ready(): # Initialize player data var player = { "name": "Warrior", "level": 5, "health": 100, "max_health": 100, "mana": 50, "inventory": ["sword", "shield", "potion"], "stats": { "strength": 15, "agility": 10, "intelligence": 8 } } # Access dictionary values print("Player name: ", player["name"]) print("Player level: ", player["level"]) print("Strength: ", player["stats"]["strength"]) # Modify values player["health"] -= 25 player["level"] += 1 print("New level: ", player["level"]) # Add new key-value pairs player["experience"] = 1500 player["gold"] = 250 # Check if key exists if player.has("gold"): print("Player has ", player["gold"], " gold") # Get value with default var karma = player.get("karma", 0) print("Karma: ", karma) # Check multiple keys if player.has_all(["health", "mana", "name"]): print("All essential stats present") # Remove key player["temporary"] = "temp_value" player.erase("temporary") # Check if empty if not player.empty(): print("Player data exists") # Get all keys var keys = player.keys() print("Player attributes: ", keys) # Get all values var values = player.values() print("First value: ", values[0]) # Dictionary size print("Number of attributes: ", player.size()) # Iterate over dictionary for key in player: if typeof(player[key]) != TYPE_ARRAY and typeof(player[key]) != TYPE_DICTIONARY: print("%s: %s" % [key, player[key]]) # Alternative dictionary syntax var enemy = { name = "Goblin", health = 50, damage = 10, loot = { gold = 25, items = ["rusty_sword"] } } print("Enemy: ", enemy.name) # Deep copy vs shallow copy var original = {"a": 1, "b": {"c": 2}} var shallow = original.duplicate() var deep = original.duplicate(true) # Modifying nested value shallow["b"]["c"] = 99 # Affects original deep["a"] = 50 # Doesn't affect original # Store game state game_data["player"] = player game_data["level"] = 1 game_data["enemies"] = [enemy] # Save/load pattern var save_dict = create_save_data() print("Save data: ", save_dict) func create_save_data() -> Dictionary: return { "version": "1.0", "timestamp": OS.get_unix_time(), "game_data": game_data } ``` -------------------------------- ### GDScript Function Definition with Arguments and Return Values Source: https://gdscript.com/tutorials/functions This example showcases various ways to define functions in GDScript, including functions with no return values, functions that return a value, functions with type-specified integer arguments, and functions with default argument values. It also demonstrates calling these functions and handling their return values. ```gdscript extends Node2D # Called when the node enters the scene tree for the first time. func _ready(): add(5, 6) # Prints 11 to Output window var sum = get_sum(2, 4) # Sets sum to 6 var my_int = add_ints(sum, 4) # Sets my_int to 10 my_int = times_2(my_int) # sets my_int to 20 move_x(self, my_int) # Move this node 20 pixels along x axis move_x(self) # Move by the default value # This function has no return value func add(a, b): print(a + b) # This function returns a value func get_sum(a, b): return a + b # This function will only accept integer arguments func add_ints(a: int, b: int): return a + b # Generate an error if the return value is not an int func times_2(n) -> int: return 2 * n # This function modifies an object that is passed by reference func move_x(node: Node2D, dx = 1.5): node.position.x += dx ``` -------------------------------- ### GDScript Numbers and Constants Source: https://context7.com/context7/gdscript-tutorials/llms.txt Demonstrates the usage of integers, floats, scientific notation, constants, and enums in GDScript for numerical operations. Includes an example of number wrapping using the modulo operator. ```gdscript extends Node2D # Integers var score = 100 var lives = 3 var hex_color = 0xFFAA00 # Floating point numbers var health = 95.5 var speed = 3.14 var large_value = 1.3e6 # Scientific notation: 1,300,000 # Constants const MAX_SPEED = 200 const PI_DOUBLED = PI * 2 const GRAVITY = 9.8 # Enums for related constants enum GameState {MENU, PLAYING, PAUSED, GAME_OVER} var current_state = GameState.PLAYING func _ready(): print("Score: ", score) print("Health: ", health) print("Max Speed: ", MAX_SPEED) print("Game State: ", current_state) # Number wrapping with modulo var wrapped_value = (score + 50) % 100 print("Wrapped value: ", wrapped_value) ``` -------------------------------- ### GDScript For Loop Examples Source: https://gdscript.com/tutorials/looping Demonstrates various applications of the 'for' loop in GDScript, including iterating over numerical ranges, strings, arrays, and dictionaries. Shows the usage of 'continue' and 'break' statements for loop control. ```GDScript # loop for n = 0 to 7 for n in 8: print(n) # Using range for n in range(8): print(n) # loop for n = 10 to 12 for n in range(10,13): print(n) # count down from 10 to 1 for n in range(10,0,-1): print(n) # loop for n = 2,4,6,8 in steps of 2 for n in range(2,9,2): print(n) # Iterate over string (array of characters) for ch in "Hello": print(ch) # Iterate over an array of numbers for x in [3,6,8,9]: print(x) # Iterate over items of a dictionary var dict = { "x": 1, "y": 2, "z": 3 } for key in dict: # Insert the key and value into a text string print("index: %s, value: %d" % [key, dict[key]]) # Using continue and break statements for n in 9: # Skip numbers below 3 if n < 3: continue # Break out of the loop for numbers above 5 if n > 5: break print(n) ``` -------------------------------- ### GDScript While Loop Example Source: https://gdscript.com/tutorials/looping Illustrates the use of a 'while' loop in GDScript, which continues execution as long as a specified boolean condition remains true. This example simulates fuel consumption to reach a top speed. ```GDScript var fuel = 1000 var speed = 0 while fuel > 0: speed += 0.12 fuel -= 1 print("Top speed = ", speed) ``` -------------------------------- ### Character Class Base Methods in GDScript Source: https://context7.com/context7/gdscript-tutorials/llms.txt Defines base methods for a character, including health management, damage taking, healing, and death. It overrides virtual methods like _process and includes custom methods for setup and item management. Dependencies include basic GDScript types and Godot's Node functionality. ```gdscript func _process(delta: float) -> void: if is_alive: update_character(delta) func setup_character() -> void: add_starting_items() func add_starting_items() -> void: inventory.append("basic_weapon") inventory.append("health_potion") func take_damage(amount: int) -> bool: if not is_alive: return false health -= amount print("%s took %d damage. Health: %d" % [character_name, amount, health]) if health <= 0: die() return true return false func heal(amount: int) -> void: health += amount if health > max_health: health = max_health print("%s healed %d. Health: %d" % [character_name, amount, health]) func die() -> void: is_alive = false health = 0 print("%s has died!" % character_name) queue_free() func update_character(delta: float) -> void: # Override this in inherited classes pass func get_health_percentage() -> float: return (health / max_health) * 100.0 ``` -------------------------------- ### GDScript Short-Circuit Evaluation Example Source: https://gdscript.com/tutorials/operators Demonstrates short-circuit evaluation in GDScript using boolean logic within an if statement. It shows how the evaluation stops as soon as the result is determined, preventing potential errors like accessing a null object's properties. The example includes checking for variable existence before accessing its properties. ```gdscript func _ready(): var x = 4 var y = 6 if x < y or x > 0: # Only x < y needs to be evaluated here print("ok") var label = Label.new() # Here we ensure that label exists before evaluating # the right side of the expression. if label and label.text == "": label.text = "Hello" ``` -------------------------------- ### GDScript Scope Bug Example (Variable Re-declaration) Source: https://gdscript.com/tutorials/variables Demonstrates a common bug in GDScript where a local variable accidentally re-declares a global variable of the same name within a function, leading to unexpected behavior. ```gdscript extends Node2D var score = 5 var new_score func add_to_score(points): # new_score is accidentally re-declared # with local scope in this indented code block var new_score = score + points func _ready(): add_to_score(1) # new_score has not been set print(new_score) # prints null ``` -------------------------------- ### GDScript Dictionaries: Define, Initialize, and Manipulate Data Source: https://gdscript.com/tutorials/dictionaries This GDScript snippet shows how to declare an empty dictionary, initialize it with key-value pairs, add/remove data, check for keys, access values, and print dictionary information. It also illustrates alternative initialization syntax and dictionary copying. ```gdscript extends Node2D # Declare an empty dictionary object var game = {} func _ready(): # Initialize a player dictionary var player = { "name": "Thor", "inventory": ["sword", "shield", "map"], "location": "Castellion", "energy": 67 } if game.empty(): # Add data to the game dictionary game["player"] = player game["score"] = 0 game["dummy"] = null if game.has("dummy"): game.erase("dummy") print(game.get("dummy", "Key not found!")) if game.has_all(["player", "score"]): print(game["player"]["name"]) player["energy"] += 1 print(game.keys().size()) print(game.size()) print(player.values()[0]) # Alternative way to initialize a dictionary var d = { a = { a1 = { a11 = 1, a12 = 2 }, a2 = 3 }, b = 1 } # Make copies of the dictionary var deep_copy = d.duplicate(true) var shallow_copy = d.duplicate() print(deep_copy) # I expected the shallow copy to be truncated print(shallow_copy) ``` -------------------------------- ### GDScript Looping Constructs Source: https://context7.com/context7/gdscript-tutorials/llms.txt Explains how to use loops in GDScript for iteration, including for loops with ranges and collections, and while loops. Demonstrates the use of 'break' to exit loops early and 'continue' to skip iterations. ```gdscript extends Node2D func _ready(): # Simple for loop (0 to 7) for i in 8: print("Count: ", i) # For loop with range for i in range(1, 11): # 1 to 10 print("Number: ", i) # Countdown loop for i in range(10, 0, -1): print("Countdown: ", i) # Step by 2 for i in range(0, 20, 2): print("Even number: ", i) # Iterate over string var word = "GODOT" for character in word: print("Letter: ", character) # Iterate over array var weapons = ["sword", "bow", "staff", "dagger"] for weapon in weapons: print("Weapon: ", weapon) # Iterate with index for i in range(weapons.size()): print("Slot ", i, ": ", weapons[i]) # Iterate over dictionary var player_stats = { "strength": 10, "agility": 8, "intelligence": 12 } for stat_name in player_stats: print("%s: %d" % [stat_name, player_stats[stat_name]]) # Break and continue for i in range(20): if i < 5: continue # Skip numbers less than 5 if i > 10: break # Stop at numbers greater than 10 print("Processing: ", i) # While loop var fuel = 100 var distance = 0 while fuel > 0: distance += 1 fuel -= 2 if distance > 40: print("Destination reached!") break print("Final distance: ", distance) print("Remaining fuel: ", fuel) # While loop with condition var attempts = 0 var success = false while attempts < 5 and not success: attempts += 1 success = try_action() print("Attempt ", attempts, ": ", success) func try_action() -> bool: return randf() > 0.5 # 50% success rate ``` -------------------------------- ### GDScript Operators and Expressions Source: https://context7.com/context7/gdscript-tutorials/llms.txt Explains the use of mathematical, assignment shortcut, boolean, comparison, and bitwise operators in GDScript. Demonstrates operator precedence and short-circuit evaluation for conditional logic. ```gdscript extends Node2D func _ready(): # Mathematical operators var result = 2 + 3 * 2 # Result: 8 (multiplication first) print("Math result: ", result) var remainder = 17 % 5 # Result: 2 print("Remainder: ", remainder) # Assignment shortcuts var counter = 10 counter += 5 # counter = 15 counter *= 2 # counter = 30 counter %= 7 # counter = 2 print("Counter: ", counter) # Boolean operators var health = 75 var has_shield = true if health > 50 and has_shield: print("Player is well protected") var can_attack = health > 0 or has_shield print("Can attack: ", can_attack) # Comparison operators var level = 5 var is_max_level = (level >= 10) # false var is_beginner = (level < 3) # false # Bitwise operators (flags) var PERMISSION_READ = 1 # Binary: 001 var PERMISSION_WRITE = 2 # Binary: 010 var PERMISSION_EXECUTE = 4 # Binary: 100 var user_permissions = PERMISSION_READ | PERMISSION_WRITE # 011 var can_read = user_permissions & PERMISSION_READ # Check flag print("Can read: ", can_read > 0) # Short-circuit evaluation var player = null if player != null and player.health > 0: print("Player is alive") else: print("No player or player dead") ``` -------------------------------- ### GDScript Basic Function Structure and Overriding Engine Functions Source: https://gdscript.com/tutorials/functions This snippet demonstrates the basic structure of a GDScript class, including member variable declarations and overriding built-in engine functions like _ready() for initialization and _process(delta) for frame-by-frame updates. It shows how to call custom functions within these entry points. ```gdscript extends Node2D # Declare member variables here. var player var enemies var score # Called when the node enters the scene tree for the first time. func _ready(): add_enemies() get_player_details() func add_enemies(): pass # Add code to do this later func get_player_details(): pass # Add the code later # Called every frame. func _process(delta): process_inputs(delta) process_enemy_activity(delta) update_score() func process_inputs(delta): pass func process_enemy_activity(delta): pass func update_score(): pass ``` -------------------------------- ### GDScript Functions and Methods Source: https://context7.com/context7/gdscript-tutorials/llms.txt Demonstrates defining and using functions in GDScript, including those with no return values, functions with return values, typed parameters, and default parameter values. Shows how functions can modify objects passed by reference. ```gdscript extends Node2D var score = 0 var player_health = 100 # Function with no return value func display_message(message: String) -> void: print("Message: ", message) # Function with return value func calculate_damage(base_damage: int, multiplier: float) -> float: return base_damage * multiplier # Function with typed parameters and return func add_score(points: int) -> int: score += points return score # Function with default parameter func heal_player(amount: float = 10.0) -> void: player_health += amount if player_health > 100: player_health = 100 # Function modifying object by reference func move_node(node: Node2D, offset: Vector2) -> void: node.position += offset ``` -------------------------------- ### GDScript Basic Node Script with Number Output Source: https://gdscript.com/tutorials/numbers A simple Godot Engine script extending Node2D that demonstrates printing a variable's value to the Output window. It shows how to initialize a variable from a constant and then modify and print it. ```gdscript extends Node2D const SPEED = 75 var number = SPEED # Called when the node enters the scene tree for the first time. func _ready(): # Print the value to the Output window of the editor print(number) number = 86 print(number) ``` -------------------------------- ### GDScript: Defining Custom Classes for OOP Source: https://context7.com/context7/gdscript-tutorials/llms.txt Shows how to define a custom class named 'Character' in GDScript, including exported properties, private variables, overriding virtual methods like '_ready', and initializing class members. ```gdscript # Define a named class class_name Character extends Node2D # Exported properties (visible in editor) export var character_name: String = "Hero" export var max_health: int = 100 export var speed: float = 200.0 export(Color, RGB) var team_color = Color.green # Private properties var health: float var is_alive: bool = true var inventory: Array = [] # Override _ready (virtual method) func _ready(): health = max_health print("%s initialized with %d health" % [character_name, health]) setup_character() ``` -------------------------------- ### Game Manager Singleton Pattern in GDScript Source: https://context7.com/context7/gdscript-tutorials/llms.txt Implements a game manager using the Singleton pattern (Autoload). It manages game state, player and enemy references, score, and uses signals for observer pattern implementation. This script is intended to be registered as an Autoload in Godot. ```gdscript extends Node # This script would be added as an Autoload (singleton) var player: Character var enemies: Array = [] var game_score: int = 0 func _ready(): print("Game Manager initialized") # Global functions accessible from anywhere func add_score(points: int) -> void: game_score += points print("Score: ", game_score) func spawn_enemy(position: Vector2) -> Enemy: var enemy = Enemy.new() enemy.position = position enemies.append(enemy) get_tree().current_scene.add_child(enemy) return enemy func get_alive_enemies() -> Array: var alive = [] for enemy in enemies: if enemy.is_alive: alive.append(enemy) return alive # Observer pattern using signals signal player_health_changed(new_health) signal enemy_defeated(enemy) signal game_over func on_player_health_change(health: int) -> void: emit_signal("player_health_changed", health) func on_enemy_defeated(enemy: Enemy) -> void: emit_signal("enemy_defeated", enemy) # Assuming 'enemies' is accessible or managed elsewhere if this is not the main manager # If this script is the main manager, 'enemies.erase(enemy)' would be here. ``` -------------------------------- ### GDScript Variables and Type System Source: https://context7.com/context7/gdscript-tutorials/llms.txt Illustrates variable declaration in GDScript, covering dynamic typing (variants) and static typing with explicit type annotations and type inference. Shows variable scope, including local and global scope. ```gdscript extends Node2D # Dynamic typing (variants) var player_name = "Thor" var score = 0 var is_active = true # Static typing - Method 1 var health: float = 100.0 var max_health: int = 100 var game_over: bool = false var inventory: Array = [] # Static typing - Method 2 (type inference) var speed := 5.0 var jump_height := 150 var can_move := true # Global scope variable var global_score = 0 func add_points(points: int) -> void: # Local scope variable var bonus = 10 global_score += points + bonus print("New score: ", global_score) func _ready(): add_points(50) # Demonstrating scope issue var temp_score = global_score modify_score() print("Global score after modify: ", global_score) func modify_score(): # Correctly modifies global variable global_score += 25 ``` -------------------------------- ### GDScript: Array Manipulation and Operations Source: https://context7.com/context7/gdscript-tutorials/llms.txt Demonstrates creating, adding, inserting, accessing, removing, checking for existence, sorting, shuffling, inverting, finding, slicing, clearing, and concatenating arrays in GDScript. It also shows multi-dimensional arrays and passing arrays by reference. ```gdscript extends Node2D func _ready(): # Create arrays var empty_array = [] var numbers = [1, 2, 3, 4, 5] var mixed = ["text", 42, true, null] var items = Array() # Add elements items.append("sword") items.append("shield") items.push_back("potion") # Same as append print("Items: ", items) # Insert at specific position items.insert(1, "helmet") print("After insert: ", items) # Access elements print("First item: ", items[0]) print("Last item: ", items[-1]) print("Second item: ", items[1]) # Array size print("Number of items: ", items.size()) # Remove elements items.remove(1) # Remove at index 1 print("After remove: ", items) items.erase("sword") # Remove by value print("After erase: ", items) # Check if array contains value if items.has("shield"): print("Shield found in inventory") # Array operations var scores = [85, 92, 78, 95, 88] scores.sort() print("Sorted scores: ", scores) scores.shuffle() print("Shuffled scores: ", scores) scores.invert() print("Inverted scores: ", scores) # Find element var position = scores.find(95) print("95 found at index: ", position) # Slice array var subset = scores.slice(1, 3) print("Subset: ", subset) # Clear array var temp = [1, 2, 3] temp.clear() print("Cleared array size: ", temp.size()) # Multi-dimensional array var grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print("Grid center value: ", grid[1][1]) # Prints 5 # Pass array by reference var inventory = ["apple", "bread"] add_item(inventory, "water") print("Modified inventory: ", inventory) # Array concatenation var list1 = [1, 2, 3] var list2 = [4, 5, 6] var combined = list1 + list2 print("Combined: ", combined) func add_item(items: Array, new_item: String) -> void: items.append(new_item) ``` -------------------------------- ### GDScript Conditional Statements Source: https://context7.com/context7/gdscript-tutorials/llms.txt Illustrates various conditional control flow structures in GDScript, including simple if, if/else, if/elif/else chains, nested conditions, ternary operators, and the match statement for switch-like behavior. ```gdscript extends Node2D enum GameState {MENU, PLAYING, PAUSED, GAME_OVER} func _ready(): var health = 75 var has_key = true # Simple if statement if health > 50: print("Player is healthy") # If/else statement if health <= 0: print("Player is dead") else: print("Player is alive") # If/elif/else chain if health >= 80: print("Excellent health") elif health >= 50: print("Good health") elif health >= 20: print("Low health") else: print("Critical health") # Nested conditions if has_key: if health > 30: print("Can open the door safely") else: print("Too weak to open door") # Ternary operator var status = "alive" if health > 0 else "dead" print("Status: ", status) var armor_bonus = 50 if has_key else 0 print("Armor bonus: ", armor_bonus) # Match statement (like switch) var state = GameState.PLAYING match state: GameState.MENU: print("Showing menu") GameState.PLAYING: print("Game is running") process_game_logic() GameState.PAUSED: print("Game paused") GameState.GAME_OVER: print("Game over") _: print("Unknown state") # Match with multiple values var direction = "north" match direction: "north", "up": print("Going up") "south", "down": print("Going down") "east", "right": print("Going right") "west", "left": print("Going left") func process_game_logic(): pass ``` -------------------------------- ### GDScript Number Assignments and Declarations Source: https://gdscript.com/tutorials/numbers Demonstrates how to declare and assign integer and floating-point values to variables in GDScript. It also shows hexadecimal number representation and the declaration of constants. ```gdscript # Integers var a = 1 var b = -23 var c = 0 var d = 0xA1Fe316 # hexadecimal # Floats var x = 1.0 var y = -43.01 var z = 1.3e6 # Constant const THE_ANSWER = 42 ``` -------------------------------- ### GDScript Array Creation, Manipulation, and Functions Source: https://gdscript.com/tutorials/arrays Demonstrates various ways to create and manipulate GDScript arrays, including instantiation, appending elements, checking array size, shuffling elements, and passing arrays by reference to functions. It highlights how changes made within a function affect the original array. ```gdscript extends Node2D func _ready(): # Ways to create an array instance var a = Array() var b = [] var c = ["a","b","c"] # Add some items to array 'a' a.append("Item 1") a.append("Item 2") # Pass array by reference to a function change(a) # Confirm that changes were made print(a[0]) # Print the size of array 'b' print(b.size()) # Shuffle the values of array 'c' c.shuffle() # This function doesn't return a value # Check that the element order was changed print_elements_of(c) func change(a): a[0] = 1 func print_elements_of(array): # Here we are using one of the Pool array types print(PoolStringArray(array).join("")) ``` -------------------------------- ### Declare GDScript Variables (Dynamic Typing) Source: https://gdscript.com/tutorials/variables Demonstrates how to declare variables in GDScript without specifying a type, allowing them to hold any data type. These variables are known as Variants. ```gdscript var score = 0 var remaining_fuel = 99.9 var paused = false var player_name = "" var selected_weapon var starting_grid_position ``` -------------------------------- ### GDScript: Define and Extend a New Class Source: https://gdscript.com/tutorials/classes This snippet demonstrates how to define a new class named 'Motorcycle' that extends 'Node2D'. It includes adding properties (make, cc, color, fuel, speed), overriding virtual methods (_ready, _process), and adding a new custom method (add_fuel). ```gdscript class_name Motorcycle extends Node2D # Add properties export(String) var make = "Kawasaki" export(int) var cc = 900 export(Color, RGB) var color = ColorN("Ninja Green") var fuel = 0.0 var speed = 0.0 # Override virtual methods func _ready(): add_fuel(17.3) func _process(delta): if fuel > 0.0: speed += delta fuel -= delta print(speed, "km/h") # Add a new method func add_fuel(litres): fuel += litres ``` -------------------------------- ### Declare GDScript Variables (Static Typing) Source: https://gdscript.com/tutorials/variables Shows two methods for declaring statically typed variables in GDScript, which enforce a specific data type for a variable, reducing bugs and improving editor support. ```gdscript # Method 1 var score: int = 0 var remaining_fuel: float = 99.9 var paused: bool = false var player_name: String = "" # Method 2 (inferring the type) var my_int := 8 var size := 32.6 var running := true var name := "" ``` -------------------------------- ### Enemy Class Extension in GDScript Source: https://context7.com/context7/gdscript-tutorials/llms.txt Extends the base Character class to create an Enemy. It includes enemy-specific properties like damage and aggro range, and implements targeting and chasing logic. This script requires the base Character class to be defined. ```gdscript class_name Enemy extends Character export var damage: int = 10 export var aggro_range: float = 200.0 var target: Node2D = null func _ready(): character_name = "Enemy" team_color = Color.red setup_character() func update_character(delta: float) -> void: if target and is_alive: chase_target(delta) func chase_target(delta: float) -> void: var direction = (target.position - position).normalized() position += direction * speed * delta func set_target(new_target: Node2D) -> void: target = new_target func attack() -> int: return damage ``` -------------------------------- ### GDScript Conditional Statements: if, else, elif Source: https://gdscript.com/tutorials/conditional-statements Demonstrates the use of if, else, and elif statements in GDScript to control program flow based on conditions. Uses indentation to define code blocks. Suitable for basic conditional logic in game development. ```GDScript extends Node2D func _ready(): var n = 6 # Inline 'if' statement if n == 6: print("n is equal to six") n = 4 # Regular 'if' statement if n == 4: print("n is equal to four") # 'else/if' statement if n == 6: print("n is equal to six") else: print("n is not equal to six") # Messy indented 'else/if' statement if n == 6: print("n is equal to six") else: if n < 6: print("n is less than six") else: print("n is greater than six") n = 8 # Tidier 'else/if' statement using 'elif' if n == 6: print("n is equal to six") elif n < 6: print("n is less than six") else: print("n is greater than six") ``` -------------------------------- ### GDScript Global and Local Variable Scope Source: https://gdscript.com/tutorials/variables Illustrates the difference between global and local variable scope in GDScript. Global variables are accessible throughout the script, while local variables are confined to specific code blocks like functions. ```gdscript extends Node2D # score has global scope in this code module var score = 5 # A function that may be called to add points to score func add_to_score(points): # points is a variable passed from outside # it has local scope in this indented code block score = score + points # This function runs when we view the scene func _ready(): add_to_score(1) # score is accessible inside this code block print(score) # prints 6 ``` -------------------------------- ### GDScript Ternary-if Expression for Conditional Assignment Source: https://gdscript.com/tutorials/conditional-statements Illustrates the use of the ternary-if expression in GDScript for concise conditional assignment of values to variables. Assigns a value based on a boolean condition. ```GDScript var paid = false var strength = 9.9 if paid else 1.0 print("Strength = ", strength) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.