@icon("res://addons/cogito/Assets/Graphics/Editor/Icon_CogitoButton.svg")
extends Node3D
signal object_state_updated(interaction_text: String) #used to display correct interaction prompts
signal pressed()
signal damage_received(damage_value:float)
@export_group("Cogito Button Settings")
Sound that plays when pressed.
@export var press_sound : AudioStream
Default prompt text when button can be pressed
@export var usable_interaction_text : String = "Press"
Toggle if button can be interacted with repeatedly or not.
@export var allows_repeated_interaction : bool = true
Forced time until button can be pressed again
@export var press_cooldown_time : float
Hint that displays after this has been used.
@export var has_been_used_hint : String
Prompt text when button has been pressed and can't be used repeatedly.
@export var unusable_interaction_text : String = "Unavailable"
Check this if player needs to have an item in the inventory to switch.
@export var needs_item_to_operate : bool
The item that the player needs to have in their inventory.
@export var required_item : InventoryItemPD
Hint that gets displayed if the switch requires an item that the player currently doesn't have.
@export var item_hint : String
Nodes that will have their interact function called when this switch is used.
@export var objects_call_interact : Array[NodePath]
@export var objects_call_delay : float = 0
var has_been_used : bool = false
var interaction_text : String
var player_interaction_component : PlayerInteractionComponent
var interaction_nodes : Array[Node]
var cogito_properties : CogitoProperties = null
var currency_check : CurrencyCheck = null
var cooldown : float
Assistant
This script describes a custom button node in Godot that can be interacted with using various gameplay mechanics. Here’s a breakdown of its components and how they can be utilized in a game:
Overview of the Script
Extends Node3D: This indicates that the script is meant to be attached to a 3D node, likely giving it a visual representation in a 3D environment.
Signals:
object_state_updated(interaction_text: String): Emitted when the state of the object changes and is used to update the interaction prompt displayed to the player.
pressed(): Emitted when the button is pressed.
damage_received(damage_value: float): Emitted when the button takes damage, possibly changing its state or functionality.
Exported Properties:
Various properties are defined to make it easy to customize the button in the Godot editor without changing the code. These properties allow you to configure sound, interaction text, cooldown behavior, and requirements for interaction.
Key Properties
press_sound: This defines the sound that will play when the button is pressed. The audio stream can be set in the editor, allowing for easy customization.
usable_interaction_text and unusable_interaction_text: These properties define the prompt provided to the player when the button can or cannot be interacted with.
allows_repeated_interaction: A boolean that determines whether the button can be pressed multiple times or only once.
press_cooldown_time: This sets a cooldown time after the button has been pressed, dictating how long the player must wait before the button becomes usable again.
needs_item_to_operate: A boolean indicating whether the player needs a specific item to use the button.
required_item: The specific item required for the button to function, which allows for implementing item-based interactions.
objects_call_interact: An array of NodePath representing nodes that should call their interact function when this button is used.
objects_call_delay: A float determining how much delay to wait before calling the interact function on the specified nodes.
User
func _ready() -> void:
self.add_to_group("interactable")
add_to_group("save_object_state")
interaction_nodes = find_children("","InteractionComponent",true) #Grabs all attached interaction components
cooldown = 0 #Enabling button to be pressed right away.
currency_check = find_child("CurrencyCheck", true, true)
if currency_check:
interaction_text = usable_interaction_text + (currency_check.currency_text if currency_check.currency_cost != 0 else "")
else:
interaction_text = usable_interaction_text
object_state_updated.emit(interaction_text)
find_cogito_properties()
func find_cogito_properties():
var property_nodes = find_children("","CogitoProperties",true) #Grabs all attached property components
if property_nodes:
cogito_properties = property_nodes[0]
The provided functions in the script implement some essential behaviors for the button object in Godot. Let's go through each part to understand how it contributes to the overall functionality of the button and how you might further enhance it.
Breakdown of Functions
_ready() function:
This function is automatically called when the node (and all its children) has entered the scene tree. It's ideal for initialization tasks.
These calls add the button to the groups "interactable" and "save_object_state". This can be useful for managing collections of objects, especially for interactions and saving/loading states.
This line retrieves all child nodes of type InteractionComponent, which presumably contain logic for handling interactions. You can call these components when the button is used.
Initializing Cooldown:
gdscript
cooldown = 0
Setting cooldown to 0 means the button can be pressed immediately upon entering the scene.
This locates a child node called CurrencyCheck if it exists. You might use this to check if the player has enough currency to interact with the button.
Updating Interaction Text:
gdscript
if currency_check:
interaction_text = usable_interaction_text + (currency_check.currency_text if currency_check.currency_cost != 0 else "")
else:
interaction_text = usable_interaction_text
object_state_updated.emit(interaction_text)
User
func interact(_player_interaction_component:PlayerInteractionComponent):
if cooldown > 0:
return
code
player_interaction_component = _player_interaction_component
# moved to press(), as currency should only be charged when press is valid
#if currency_check and currency_check.currency_cost != 0:
#if not currency_check.check_for_currency(player_interaction_component.get_parent()):
#player_interaction_component.send_hint(null, currency_check.not_enough_currency_hint)
#return
if !allows_repeated_interaction and has_been_used:
player_interaction_component.send_hint(null, has_been_used_hint)
return
if needs_item_to_operate:
if check_for_item() == true:
press()
else:
press()
func press():
# only run the currency check once the press is validated and triggered
# otherwise you can charge for a transaction and still not press the button
if currency_check and currency_check.currency_cost != 0:
if not currency_check.check_for_currency(player_interaction_component.get_parent()):
player_interaction_component.send_hint(null, currency_check.not_enough_currency_hint)
return
code
pressed.emit()
Audio.play_sound_3d(press_sound).global_position = global_position
if !allows_repeated_interaction:
has_been_used = true
interaction_text = unusable_interaction_text
object_state_updated.emit(interaction_text)
else:
cooldown = press_cooldown_time
if !objects_call_interact:
return
for nodepath in objects_call_interact:
await get_tree().create_timer(objects_call_delay).timeout
if nodepath != null:
var object = get_node(nodepath)
object.interact(player_interaction_component)
func check_for_item() -> bool:
var inventory = player_interaction_component.get_parent().inventory_data
for slot_data in inventory.inventory_slots:
if slot_data != null and slot_data.inventory_item == required_item:
player_interaction_component.send_hint(null, required_item.name + " used.") # Sends a hint with the key item name.
if slot_data.inventory_item.discard_after_use:
inventory.remove_item_from_stack(slot_data)
# inventory.remove_slot_data(slot_data) (removed on 20240913, leaving line just in case there's bugs.
return true
Assistant
The provided functions further enhance the button's interaction capabilities within a Godot game environment. Let's break down each part and suggest improvements or enhancements where applicable.
This function is the main entry point for handling player interactions with the button.
Cooldown Check:
gdscript
if cooldown > 0:
return
It immediately exits if the cooldown is active, preventing interaction until the cooldown expires.
Currency Check (commented):
The commented-out section checks for currency before allowing interaction. This has moved to the press() function to ensure currency is only decremented when the interaction is valid.
Repeated Interaction Check:
gdscript
if !allows_repeated_interaction and has_been_used:
player_interaction_component.send_hint(null, has_been_used_hint)
return
If the button isn't set up for repeated use and has already been used, a hint is sent to the player.
Item Requirement Check:
If the button requires an item to operate, it checks for that item.
gdscript
if needs_item_to_operate:
if check_for_item() == true:
press()
else:
press()
If an essential item is present, it calls press(), proceeding with the interaction.
press():
This function contains the main logic for what happens when the button is successfully pressed.
It checks for sufficient currency before allowing the press:
gdscript
if currency_check and currency_check.currency_cost != 0:
if not currency_check.check_for_currency(player_interaction_component.get_parent()):
player_interaction_component.send_hint(null, currency_check.not_enough_currency_hint)
return
This class handles systeminc properties. Needs to be attached to a CogitoObject to work properly. For proper processing, said Object needs to have a signal hooked up to call check_for_systemic_interactions(collider).
class_name CogitoProperties
signal has_ignited()
signal has_been_extinguished()
signal deal_burn_damage(burn_damage_amount:float)
signal has_become_wet()
signal has_become_dry()
signal has_become_electric()
signal has_lost_electricity()
@onready var audio_stream_player_3d: AudioStreamPlayer3D = AudioStreamPlayDamageTimer
@onready var reaction_timer: Timer = $ReactionTimer
Assistant
The CogitoProperties class you provided is a complex script designed to handle various systemic properties of an object in a Godot game. This class uses signals and properties related to elemental and material interactions, such as burning, getting wet, or becoming electrified. Let’s go through the components step-by-step and discuss their functionality, potential improvements, and how this can be integrated into a game environment.
Extends Node3D, meaning it can be placed in a 3D scene.
The class is named CogitoProperties, making it easier to manage and reference within the Godot editor and scripts.
Signals:
Various signals are defined to handle specific interactions (e.g., has_ignited, has_been_extinguished, etc.). This allows other parts of your game to listen for and respond to these states.
For example, functions or other nodes in the game can connect to these signals to trigger events when, say, a fire ignites or extinguishes, allowing for dynamic gameplay responses.
These enums define constant values for elemental and material properties, facilitating management of bitflags and making the code more readable.
Exported Properties:
Properties like elemental_properties, material_properties, reaction_threshold_time, and others are exported, meaning they can be modified from the Godot editor.
The use of @export_flags allows you to check for multiple properties (bitflags), which simplifies interactions since you're efficiently using integer flags to represent state.
Audio and Visual Effects:
Numerous audio streams and objects are exported, allowing you to define sound and visual effects that happen on specific state changes (e.g., when an object ignites or becomes wet).
await get_parent().is_node_ready()
if ignite_on_ready:
set_on_fire()
if electric_on_ready:
make_electric()
if elemental_properties == ElementalProperties.WET:
make_wet()
func start_reaction_threshold_timer(passed_collider: Node3D):
# Quick check to see if the collider has any CogitoProperties.
if( !passed_collider.cogito_properties):
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", "Collider " + passed_collider.name + " has no properties.")
return
code
# Saving passed collider to make sure we're reaction to the right thing.
reaction_collider = passed_collider
add_systemic_body(passed_collider)
# Starting the reaction timer.
if reaction_timer.is_stopped():
reaction_timer.wait_time = reaction_threshold_time
reaction_timer.start()
# Quick check to see if the collider has any CogitoProperties.
if( !passed_collider.cogito_properties):
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", "Collider " + passed_collider.name + " has no properties.")
return
remove_systemic_body(passed_collider)
Assistant
The functions you've provided are part of the CogitoProperties class, enhancing its capabilities to handle reactions to elemental interactions like burning, getting wet, or becoming electrified. Let's dive into the details of each function and discuss how they work and how you might want to enhance or modify them.
Breakdown of Functions
_ready():
This method is called when the node is initialized in the scene tree.
Connections are made to the timeout signal of reaction_timer and damage_timer, binding them to their respective handling functions. When the timer reaches its duration, it triggers these functions.
Awaiting Node Readiness:
gdscript
await get_parent().is_node_ready()
This line ensures that the parent node of this object is fully initialized and ready before proceeding with further setup.
Initial Property Checks:
gdscript
if ignite_on_ready:
set_on_fire()
if electric_on_ready:
make_electric()
if elemental_properties == ElementalProperties.WET:
make_wet()
Based on the initialization parameters, it sets the object's state to burning, electrified, or wet. These functions would handle activating the appropriate effects and states.
This method is called when an object (the collider) reacts with the current object.
Checking for Properties:
It first checks if the passed collider has the CogitoProperties component. If it does not, it logs a message and returns early:
gdscript
if (!passed_collider.cogito_properties):
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", "Collider " + passed_collider.name + " has no properties.")
return
User
If the passed_collider is the reaction_collider, then this reaction needs to be stopped.
code
if passed_collider == reaction_collider:
print(get_parent().name , ": Passed collider and current reaction collider match! Reaction timer is stopped is ", reaction_timer.is_stopped())
if !reaction_timer.is_stopped():
print(get_parent().name , " has stopped reaction timer as the collider ", passed_collider, " is no longer in contact.")
reaction_timer.stop()
if reaction_bodies.size() == 0:
if !electric_on_ready:
loose_electricity()
func check_for_systemic_reactions():
if !reaction_collider:
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd","Reaction collider was null.")
return
if !reaction_collider.cogito_properties:
# Case where the object has no properties defined.
print("Collider ", reaction_collider.name, " has no properties.")
return
code
if reaction_collider.cogito_properties:
### FIRE REACTIONS
if reaction_collider.cogito_properties.is_on_fire:
if elemental_properties & ElementalProperties.FLAMMABLE:
print(get_parent().name, ": Touched burning collider ", reaction_collider.name, ". I'm flammable, igniting self.")
set_on_fire()
else:
print(get_parent().name, ": Touched collider ", reaction_collider.name, " which is on fire, but I'm not flammable, so nothing happens.")
if elemental_properties & ElementalProperties.WET:
print(get_parent().name, ": Touched burning collider ", reaction_collider.name, ". I'm wet so I'll extinguish the collider.")
reaction_collider.cogito_properties.extinguish()
if elemental_properties & ElementalProperties.CONDUCTIVE: ### ELECTRICITY REACTIONS
if is_electric:
print("Electrified ", get_parent().name, " touched condictive collider ", reaction_collider.name, ". Trying to pass on electricity!")
reaction_collider.cogito_properties.make_electric()
if reaction_collider.cogito_properties.is_electric:
print(get_parent().name, ": Touched by electrified collider ", reaction_collider.name, ". Getting electric.")
make_electric()
print("Collider ", reaction_collider.name, " elemental properties: ", reaction_collider.cogito_properties.elemental_properties)
match reaction_collider.cogito_properties.elemental_properties:
ElementalProperties.WET: ### WATER REACTIONS
if is_on_fire:
print(get_parent().name, ": Touched by wet collider ", reaction_collider.name, " while on fire. Extinguishing self.")
extinguish()
make_wet()
else:
print(get_parent().name, ": Touched by wet collider ", reaction_collider.name, " but wasn't on fire. Getting wet.")
make_wet()
Assistant
The code you've provided is part of a broader interaction system that allows objects to respond to various elemental conditions (like fire, electricity, and water) dynamically. Let's break down the components, the logic involved, and suggestions for improvements.
Breakdown of Functions
Stopping the Reaction Timer:
gdscript
if passed_collider == reaction_collider:
print(get_parent().name , ": Passed collider and current reaction collider match! Reaction timer is stopped is ", reaction_timer.is_stopped())
if !reaction_timer.is_stopped():
print(get_parent().name , " has stopped reaction timer as the collider ", passed_collider, " is no longer in contact.")
reaction_timer.stop()
This code checks if the passed_collider (the object that is currently colliding with the other object) is the same as the reaction_collider (the collider currently being reacted to).
If they match and the reaction timer is running, it prints debug information, then stops the reaction timer.
Handling Loose Electricity:
gdscript
if reaction_bodies.size() == 0:
if !electric_on_ready:
loose_electricity()
Here, it checks if there are any reaction bodies being tracked. If none are found and the object is not ready for electric reactions, it calls loose_electricity(), likely to remove any electrical state from the object.
Checking for Systemic Reactions:
gdscript
func check_for_systemic_reactions():
if !reaction_collider:
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd","Reaction collider was null.")
return
if !reaction_collider.cogito_properties:
# Case where the object has no properties defined.
print("Collider ", reaction_collider.name, " has no properties.")
return
func set_on_fire():
if elemental_properties & ElementalProperties.FLAMMABLE:
is_on_fire = true
if spawn_on_ignite:
spawn_elemental_vfx(spawn_on_ignite)
Audio.play_sound_3d(audio_igniting).position = self.position
has_ignited.emit()
code
if burn_damage_amount > 0:
start_burn_damage_timer()
audio_stream_player_3d.stream = audio_burning
audio_stream_player_3d.play()
else:
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", get_parent().name + " is not FLAMMABLE.")
func start_burn_damage_timer():
if damage_timer.is_stopped():
damage_timer.wait_time = burn_damage_interval
damage_timer.start()
func apply_burn_damage():
deal_burn_damage.emit(burn_damage_amount)
# Calling damage received on Cogito Object or Enemy parent node.
get_parent().damage_received.emit(burn_damage_amount)
code
if is_on_fire:
start_burn_damage_timer()
Assistant
The functions you've provided are implementations for handling elemental state changes within your CogitoProperties class. These functions focus on making the object conductive, flammable, wet, or dry, as well as managing the effects of being on fire (such as dealing burn damage). Let's break down their functionality and consider enhancements or improvements.
Similar to make_conductive(), this toggles the FLAMMABLE state.
make_wet():
gdscript
func make_wet():
if( elemental_properties & ElementalProperties.WET):
pass
else:
elemental_properties = elemental_properties ^ ElementalProperties.WET
if is_on_fire:
extinguish()
if spawn_on_wet:
spawn_elemental_vfx(spawn_on_wet)
has_become_wet.emit()
This set the object as wet if it isn’t already, extinguishes it if it’s on fire, spawns visual effects defined in spawn_on_wet, and emits the has_become_wet signal.
The use of a check before toggling the wet state is efficient, preventing unnecessary state changes.
func spawn_elemental_vfx(vfx_packed_scene:PackedScene):
var spawned_object = vfx_packed_scene.instantiate()
get_parent().add_child.call_deferred(spawned_object)
code
# If max spawned vfx is reached, all spawned vfx will be cleared.
if spawned_effects.size() <= max_spawned_vfx + 1:
clear_spawned_effects()
spawned_effects.append(spawned_object)
spawned_object.position = Vector3(0,0,0)
func add_systemic_body(body: Node3D):
if reaction_bodies.find(body) == -1:
reaction_bodies.append(body)
func remove_systemic_body(body: Node3D):
var index_in_reaction_bodies : int = reaction_bodies.find(body)
if index_in_reaction_bodies != -1:
reaction_bodies.remove_at(index_in_reaction_bodies)
func recheck_systemic_reactions():
if reaction_bodies.size() < 1:
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", get_parent().name + " systemic properties: Can't recheck reactions as there's no reaction bodies stored.")
return
code
for reaction_body in reaction_bodies:
start_reaction_threshold_timer(reaction_body)
Assistant
The code you've shared continues to build the CogitoProperties class, focusing on managing the extinguishing of fire, electricity interactions, and associated effects. Let's analyze the purpose and functionality of each function, while also considering potential improvements and enhancements.
This function stops any ongoing fire effects. It sets the is_on_fire flag to false, stops the damage timer if it is running, and plays the extinguishing sound effect. The effects that were spawned while on fire are cleared, and it emits the has_been_extinguished signal.
clear_spawned_effects():
gdscript
func clear_spawned_effects():
for node in spawned_effects:
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", "Clearing out spawned effect " + node.name)
node.queue_free()
spawned_effects.clear()
This method iterates through the spawned_effects list and frees each node from the scene, logging each action, and finally clears the list. It ensures that any visual effects that were created earlier are removed.
make_electric():
gdscript
func make_electric():
if elemental_properties & ElementalProperties.CONDUCTIVE:
is_electric = true
spawn_elemental_vfx(spawn_on_electrified)
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", get_parent().name + " has become electric.")
has_become_electric.emit()
recheck_systemic_reactions()
else:
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", get_parent().name + " is not CONDUCTIVE.")
Not yet included in a published release.
Variables
has_been_used: A boolean variable to track whether the button has already been pressed.
interaction_text: Stores the current interaction text to be displayed to the player.
player_interaction_component: A reference to the player's interaction component; could be used to manage interaction logic or checks.
interaction_nodes: An array to hold any nodes that are directly tied to this button's interactions.
cogito_properties and currency_check: Likely used to handle other types of interactions or checks related to the game's mechanics.
cooldown: Stores the current cooldown time after a button press; useful for managing time-based interactions.
How to Use in Game Development
Attach the Script to a 3D Node: You can attach this script to 3D nodes representing buttons in your scene.
Set Up the Inspector: Use the Godot editor to configure the properties for your button easily. Customize the sound, texts, item requirements, etc.
Implement Interaction Logic: You will need to define the _ready() and other relevant functions to set up the initial state and behaviors (e.g., handling input to call the pressed signal).
Connect Signals: You should connect the emitted signals to other parts of your game, such as updating UI prompts or triggering other game actions.
Implement Item Check Logic: If the button requires an item to operate, ensure you implement the logic for checking the player's inventory and responding appropriately.
By building on this script, you can create complex interactive elements for your game that respond to player actions and game state changes.
Depending on whether the CurrencyCheck node is present and has a non-zero cost, the interaction text is updated to include currency information. The text is then emitted to communicate to other parts of the game (like UI) about the button's current state.
Finding Cogito Properties:
gdscript
find_cogito_properties()
Calls another function which will find specific components related to the button.
find_cogito_properties() function:
This function searches for any child nodes with the name CogitoProperties.
It assigns the first found instance to the variable cogito_properties, allowing you to later reference properties or methods defined in that component.
_physics_process(delta: float) function:
This function is called every frame while the node is in the scene and is suitable for continuous updates.
Cooldown Logic:
gdscript
if cooldown > 0:
cooldown -= delta
If the cooldown variable is greater than zero, it’s decremented by delta (the time passed since the last frame). This effectively creates a timer that allows the button to be pressed only after the cooldown period has ended.
Additional Enhancements
Press Logic: You will need to implement the logic for what happens when the button is pressed, checking if the cooldown is active, whether repeated interactions are allowed, and checking for any required items.
gdscript
func _on_ButtonPressed() -> void:
if cooldown <= 0: # Check cooldown
if not allows_repeated_interaction and has_been_used:
interaction_text = unusable_interaction_text
object_state_updated.emit(interaction_text)
return
if needs_item_to_operate and not has_required_item():
interaction_text = item_hint
object_state_updated.emit(interaction_text)
return
# Play sound if defined
if press_sound:
get_tree().call_group("audio", "play_sound", press_sound)
cooldown = press_cooldown_time if press_cooldown_time > 0 else cooldown
has_been_used = true
pressed.emit() # Emit the pressed signal
call_interaction_nodes() # Call each interaction node's `interact` function
Handling Interactions: You may want to implement the call_interaction_nodes() method to call the interact() function on each child node listed in interaction_nodes.
Saving/Loading State: Since the button is part of a group for saving state, you might want to implement methods for saving and loading its state (i.e., whether it has been pressed).
UI Integration: Ensure that your UI components are set to listen for the object_state_updated signal so they can update the interaction prompts dynamically.
With these implementations, your button should be quite functional in the context of a Godot game, allowing for dynamic interactions based on conditions such as cooldowns, player inventory, and UI updates.
code
if item_hint != "":
player_interaction_component.send_hint(null,item_hint) # Sends the key hint with the default hint icon.
return false
Calling Interaction on Other Nodes:
It waits for the specified delay before calling the interact function on other nodes, allowing objects linked to the button to respond accordingly:
gdscript
for nodepath in objects_call_interact:
await get_tree().create_timer(objects_call_delay).timeout
if nodepath != null:
var object = get_node(nodepath)
object.interact(player_interaction_component)
This function is called when damage is received and triggers the interact() function with the player's interaction component. This can enable interaction with the button in response to damage events.
check_for_item() -> bool:
This function checks if the player has the required item to activate the button. If found, it returns true, sends a confirmation hint, and removes the item if it is marked for discard.
If the required item is absent, it will send a hint regarding the missing item.
set_state():
This function updates the interaction text based on the button's state. It emits the object_state_updated signal to update any UI or other components observing this state.
save():
This method constructs and returns a dictionary containing essential details about the button's state for saving. It includes position and rotation for potential restoration later.
Suggestions for Improvement
Error Handling:
Ensure that any access to nodes and properties is wrapped with checks to prevent runtime errors (e.g., checking if a node is null before calling methods).
Async Handling in press():
If you have a non-blocking way to process the interactions or currency checks asynchronously, consider implementing coroutines or leveraging signals to optimize responsiveness.
Documentation:
Adding comments detailing the purpose of each function and significant logic can improve maintainability, especially as the project grows.
Consider Dynamic Items:
If the game allows for the player to pick up or discard items dynamically, ensure that your check_for_item() method properly reflects the player's current inventory status in real time.
User Feedback:
Consider providing additional visual or audio cues for different states (e.g., if a player tries to press the button without sufficient currency instead of just sending hints).
Testing State Restoration:
Ensure the save() function's output is correctly restored elsewhere in the game when loading, possibly incorporating a load function based on the saved state_dict.
By incorporating these suggestions, you can enhance usability, performance, and maintainability within your game, ultimately leading to a better experience for players interacting with the widget.
er
3
D
@
o
n
r
e
a
d
y
v
a
r
d
ama
g
et
im
er
:
Timer=
Bitflag for elemental properties. Gets handled when a collision calls "check_for_systemic_interactions(collider)".
@export_flags("CONDUCTIVE", "FLAMABLE", "WET") var elemental_properties: int = 0
Bitflag for material properites. Gets handled when a projectile or similar damage call applies. SOFT materials can get damaged by SOFT projectiles.
@export_flags("SOFT") var material_properties: int = 0
Time it takes for a property state change to happen. E.g. an object only ignites if exposed to fire for at least 1 second.
@export var reaction_threshold_time : float = 1.0
The maximum amount of spawned vfx. Lower this to reduce potential performance issues.
@export var max_spawned_vfx : int = 5
@export_group("Burn Parameters")
Sets if the object should ignite itself on ready. Needs to be flammable for this to work.
@export var ignite_on_ready : bool
Amount of damage dealt to the health component while object is on fire.
@export var burn_damage_amount : float
Interval the burn damage is applied in seconds.
@export var burn_damage_interval : float = 1.0
@export_group("Electricity Parameters")
Sets if the object should become electrified on ready. Needs to be conductive for this to work.
@export var electric_on_ready : bool
@export_group("VFX PackedScenes")
PackedScene of VFX etc that gets spawned when object ignites.
@export var spawn_on_ignite : PackedScene
PackedScene of VFX etc that gets spawned when object gets wet.
@export var spawn_on_wet : PackedScene
PackedScene of VFX etc that gets spawned when object is electrified
@export var spawn_on_electrified : PackedScene
@export_group("Audio")
@export var audio_igniting : AudioStream
@export var audio_burning : AudioStream
@export var audio_extinguishing : AudioStream
@export_group("Debuging")
If turned on, this object will print log messages (only if the global is_logging is turned on as well!)
@export var is_logging : bool = true
var reaction_collider : Node3D = null
var spawned_effects : Array[Node] # Used to store and clear out spawned effects
var is_on_fire : bool = false
var is_electric : bool = false
var player_is_touching : bool = false
var player_node : Node3D = null
var reaction_bodies : Array[Node3D] #Used to keep track of bodies with systemic properties.
PackedScene
spawned_effects could be used to keep track of active visual effects in the game that may need to be cleaned up afterward.
State Flags:
Flags like is_on_fire, is_electric, and player_is_touching help manage the state of the object. This is important for interaction logic, guiding behavior based on whether conditions such as being ignited or electrified are present.
Reacting to Environmental Changes:
Signals and checks would typically be placed in methods that handle triggers, such as when an object collides with something or when a timer indicates that a state change should occur. These methods would be responsible for managing damage and visual/auditory feedback.
Suggested Enhancements and Considerations
Initialization Logic:
Implement logic in _ready() or a dedicated initialization function that sets up the initial state based on exported properties. For example, check if ignite_on_ready or electric_on_ready is true.
gdscript
func _ready() -> void:
if ignite_on_ready:
ignite()
if electric_on_ready:
electrify()
Managing State Changes:
Create helper functions to handle state changes, which will emit signals and play audio when certain events occur.
You may need a method to handle collision checks and invoke the appropriate reactions:
gdscript
func check_for_systemic_interactions(collider: Node):
if collider.is_in_group("fire"):
ignite()
elif collider.is_in_group("water"):
become_wet()
Testing and Debugging:
Ensure that the is_logging property can be toggled to print relevant messages during gameplay. Implement logging within state change methods to help diagnose issues:
gdscript
if is_logging:
print("Object ignited!")
Performance Considerations:
Since visual effects can impact performance, ensure that you don’t exceed the max_spawned_vfx count to avoid performance degradation.
Tweaks for VFX and Audio:
For managing spawned effects and audio, consider using a pool system or limiting the total number of active effects to optimize performance.
Cleanup:
Create a cleanup method to handle the destruction of spawned effects when the object transitions to certain states or is destroyed.
Integration into the Game
To use the CogitoProperties class effectively within your game:
Attach this script to objects that need to react to environmental elements like fire, water, or electricity.
Use the various signals to connect to other systems within your game, such as updating UI elements or triggering animations.
Make sure you have the appropriate collider setups in the node tree to trigger interactions properly.
Test interactions thoroughly to ensure that your properties and their transitions work well in all possible scenarios.
By structuring your class in this way, you create a robust system for handling complex interactions in your game's environment that can significantly enhance gameplay dynamics.
Starting the Reaction Timer:
It saves the passed collider in reaction_collider, calls add_systemic_body(passed_collider), which likely registers the collider for future checks, and starts the reaction_timer with the defined wait time:
gdscript
if reaction_timer.is_stopped():
reaction_timer.wait_time = reaction_threshold_time
reaction_timer.start()
This function appears to be called to determine if an event should interrupt the current reaction timer.
Similar Property Check:
Like in the previous function, it checks if the collider has the CogitoProperties component and logs a message if it doesn’t:
gdscript
if (!passed_collider.cogito_properties):
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", "Collider " + passed_collider.name + " has no properties.")
return
Removing a Systemic Body:
The collider will be removed from systemic tracking, allowing you to manage interactions dynamically, especially if collisions or interactions change.
Suggested Enhancements
To enhance your existing code, consider the following options:
Error Handling and Feedback:
Implement additional error handling in case something goes wrong. For instance, what if reaction_collider is null when you try to reference it later?
Clearer Function Naming:
Rename check_for_reaction_timer_interrupt to something more indicative of its purpose, such as handle_reaction_interrupt or interrupt_reaction.
Optimization of State Management:
The functions set_on_fire(), make_electric(), and make_wet() should be responsible for handling state-related logic entirely. Consider logging and checking states within those functions to avoid repeating conditions in the ready function.
Debug Logs:
Use logging strategically to better track the flow of reactions and interactions. For example, you might want to log foundational changes in state that occur over the gameplay loop.
Timer Management:
Depending on the complexity of your interactions, you may want to consider additional conditions under which timers can be stopped or reset.
For instance, if multiple colliders are interacting at once or a state change occurs before the timer completes, appropriately managing these states can help prevent conflicting actions.
Commenting and Documentation:
Include comments explaining the purpose of each method and major code blocks, especially where decisions are made based on the object's state. This will be helpful for future developers (or for yourself) if changes need to be made later.
Integration into Gameplay
Collisions: Ensure that this class responds to collision events in the scene. You’ll likely need to utilize _on_body_entered or similar methods to call start_reaction_threshold_timer().
Visual and Audio Feedback: Assuming you have mechanisms in place for playing audio and spawning visual effects, link these methods into your state-change functions for a more immersive experience.
Testing: Rigorously test interactions in various scenarios to ensure that timers function correctly and that the expected visual/audio effects occur.
In conclusion, your provided code is already quite comprehensive. By following the suggestions outlined here, you can further improve the robustness and clarity of your system for handling elemental interactions within the game.
The function begins by ensuring reaction_collider exists and has the necessary properties. If not, debug logging is performed, and the function returns.
Fire Reactions:
gdscript
if reaction_collider.cogito_properties.is_on_fire:
if elemental_properties & ElementalProperties.FLAMMABLE:
print(get_parent().name, ": Touched burning collider ", reaction_collider.name, ". I'm flammable, igniting self.")
set_on_fire()
else:
print(get_parent().name, ": Touched collider ", reaction_collider.name, " which is on fire, but I'm not flammable, so nothing happens.")
if elemental_properties & ElementalProperties.WET:
print(get_parent().name, ": Touched burning collider ", reaction_collider.name, ". I'm wet so I'll extinguish the collider.")
reaction_collider.cogito_properties.extinguish()
If the collider is on fire, it checks if the object is flammable. If it is, the object ignites itself. If not, a message shows that nothing happens.
If the object is wet, it extinguishes the burning object.
Electricity Reactions:
gdscript
if elemental_properties & ElementalProperties.CONDUCTIVE: ### ELECTRICITY REACTIONS
if is_electric:
print("Electrified ", get_parent().name, " touched conductive collider ", reaction_collider.name, ". Trying to pass on electricity!")
reaction_collider.cogito_properties.make_electric()
if reaction_collider.cogito_properties.is_electric:
print(get_parent().name, ": Touched by electrified collider ", reaction_collider.name, ". Getting electric.")
make_electric()
Here, it checks if the object is conductive and whether it is electric. If both conditions are met, electricity can be passed or absorbed, respectively.
Water Reactions:
gdscript
match reaction_collider.cogito_properties.elemental_properties:
ElementalProperties.WET: ### WATER REACTIONS
if is_on_fire:
print(get_parent().name, ": Touched by wet collider ", reaction_collider.name, " while on fire. Extinguishing self.")
extinguish()
make_wet()
else:
print(get_parent().name, ": Touched by wet collider ", reaction_collider.name, " but wasn't on fire. Getting wet.")
make_wet()
If the reaction collider is wet, it checks the object's state. If the object is on fire, it extinguishes itself and gets wet. Otherwise, it just gets wet.
Suggestions for Improvement
Performance Optimization:
Consider using switch-case constructs or dictionaries to manage elemental reactions. This might streamline adding new states and properties in the future.
Error Handling:
Consider adding more rigorous error handling when accessing properties of reaction_collider. If for some reason, it doesn't have cogito_properties, you may run into a null reference error. Make sure to check if it’s valid before accessing any attributes.
Consolidate Logging:
Instead of duplicating logging statements, consider creating a utility function for logging, which can streamline your code:
gdscript
func log_event(event_message: String):
if is_logging:
print(event_message)
Then use it throughout the code to log messages.
Reactive Properties Management:
When checking properties like is_on_fire or is_electric, maintain a clear and singular source of truth for each object's state. Consider encapsulating state management within the CogitoProperties class or similar to avoid scattered state checks.
Timers and State Changes:
Ensure that state changes, like igniting or electrifying, have a clear method for transitioning back or stopping in conditions where they may change (e.g., reacting to water extinguishing fires, or state resets).
Documentation:
Include comments to document specific logic or decisions made, especially where you determine state transitions. It would help future developers (or yourself) to understand the reasoning behind the implementations.
Integration and Testing
Test Interactions: Rigorously test interactions to ensure the expected behaviors occur without unintended consequences. Test cases such as an electrified object touching a wet environment, or characters that may have various elemental properties.
Visual and Audio Feedback: Implement visual cues for elemental states (e.g., flames for fire, sparks for electricity) alongside audio feedback for a more immersive experience when reactions take place.
By structuring your code in this way and implementing the suggested improvements, you should create a robust and versatile interaction system that adds depth to your game's mechanics.
This function will remove the wet state, clear any visual effects associated with being wet, and emit a signal that the object has become dry.
set_on_fire():
gdscript
func set_on_fire():
if elemental_properties & ElementalProperties.FLAMMABLE:
is_on_fire = true
if spawn_on_ignite:
spawn_elemental_vfx(spawn_on_ignite)
Audio.play_sound_3d(audio_igniting).position = self.position
has_ignited.emit()
if burn_damage_amount > 0:
start_burn_damage_timer()
audio_stream_player_3d.stream = audio_burning
audio_stream_player_3d.play()
else:
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", get_parent().name + " is not FLAMMABLE.")
This checks if the object is flammable before setting it on fire. If flammable, it plays a sound, spawns visual effects, emits the has_ignited signal, and starts dealing burn damage if applicable.
If it's not flammable, a debug message is logged.
start_burn_damage_timer():
gdscript
func start_burn_damage_timer():
if damage_timer.is_stopped():
damage_timer.wait_time = burn_damage_interval
damage_timer.start()
This function initializes the burn damage timer if it’s not already running, ensuring that damage is applied at the correct intervals.
apply_burn_damage():
gdscript
func apply_burn_damage():
deal_burn_damage.emit(burn_damage_amount)
get_parent().damage_received.emit(burn_damage_amount)
if is_on_fire:
start_burn_damage_timer()
This function emits signals to deal burn damage and communicate with the parent node (such as an enemy or character) about the damage received.
It checks if the object is still on fire before re-starting the timer, creating a loop of damage until the fire is extinguished.
Suggestions for Improvement
Toggle Functions:
If you're using the XOR operation to toggle states, consider adding separate functions for setting and clearing properties for clarity, such as set_conductive(), set_non_conductive(), etc. That way, the intent of the function is clearer.
Audio Management:
It's beneficial to manage audio streams efficiently, ensuring that sounds don't overlap unnecessarily or cause performance issues. You could manage this by checking if the sound is already playing before starting a new one.
Effect Management:
The clear_spawned_effects() function in make_dry() might need to explicitly specify what effects to remove or keep track of spawned effects in an array or other data structure to implement clearer cleanup functionality.
Conditional Logic Streamlining:
In make_wet(), you might want to clarify the logic further:
gdscript
func make_wet():
if elemental_properties & ElementalProperties.WET:
return # already wet, no action needed
elemental_properties ^= ElementalProperties.WET
if is_on_fire:
extinguish()
else:
if spawn_on_wet:
spawn_elemental_vfx(spawn_on_wet)
has_become_wet.emit()
Early returns can help reduce the complexity of the function.
Documentation and Comments:
Adding comments to critical functions, especially those dealing with gameplay mechanics, can assist future developers (or yourself) in understanding the logic flow more easily.
Visual Feedback:
Consider integrating visual feedback alongside audio (like smoke when something is ignited) to enhance player immersion and emulate realistic behaviors.
Integration into Gameplay
Collisions and Interaction Triggers: Ensure that the methods for setting states (like set_on_fire() or make_wet()) are called adequately in response to player actions or environmental triggers.
Testing: Extensively test these features in various scenarios, such as multi-element interactions (like an electrified wet object) to ensure that all properties are responding coherently without conflicts.
With these functions, you have a solid base for effectively managing elemental properties in your game. By implementing the suggested improvements, you can enhance the clarity, maintainability, and performance of your code while increasing the overall richness of gameplay mechanics.
This function checks if the object is conductive. If it is, it sets is_electric to true, spawns the relevant visual effects, logs the action, and emits the has_become_electric signal. It also calls recheck_systemic_reactions(), likely to check for any new interactions due to the electric state.
func spawn_elemental_vfx(vfx_packed_scene: PackedScene):
var spawned_object = vfx_packed_scene.instantiate()
get_parent().add_child.call_deferred(spawned_object)
# If max spawned vfx is reached, all spawned vfx will be cleared.
if spawned_effects.size() <= max_spawned_vfx + 1:
clear_spawned_effects()
spawned_effects.append(spawned_object)
spawned_object.position = Vector3(0,0,0)
This function instantiates a visual effect from a packed scene and adds it as a child to the parent node. It checks if the number of spawned effects exceeds a maximum limit and clears them if it does. The effect's position is set, though it’s currently set to the origin. This may need to be adjusted based on your design.
add_systemic_body(body: Node3D):
gdscript
func add_systemic_body(body: Node3D):
if reaction_bodies.find(body) == -1:
reaction_bodies.append(body)
This function adds a body to the reaction_bodies list, ensuring that it only adds it if it isn’t already in the list. This prevents duplicates.
remove_systemic_body(body: Node3D):
gdscript
func remove_systemic_body(body: Node3D):
var index_in_reaction_bodies: int = reaction_bodies.find(body)
if index_in_reaction_bodies != -1:
reaction_bodies.remove_at(index_in_reaction_bodies)
This method removes a body from the reaction_bodies list if it exists, ensuring state management is clear.
recheck_systemic_reactions():
gdscript
func recheck_systemic_reactions():
if reaction_bodies.size() < 1:
CogitoGlobals.debug_log(is_logging, "cogito_properties.gd", get_parent().name + " systemic properties: Can't recheck reactions as there's no reaction bodies stored.")
return
for reaction_body in reaction_bodies:
start_reaction_threshold_timer(reaction_body)
This function checks if there are any reaction_bodies and, if present, iterates through them to restart the reaction threshold timer. It logs a message if no bodies are available to check.
Suggestions for Improvement
Improve VFX Management:
When spawning visual effects, make sure to position the effects meaningfully relative to the parent object. For example, if an object is on fire, the visual effects should appear around its boundaries. Currently, they are all set to the origin (Vector3(0,0,0)), which may not be intended.
gdscript
spawned_object.position = self.position # or use a specific offset
Error Handling:
In methods like make_electric(), you could enhance error handling and logging. Consider logging additional context about the state of the object if it fails to become electric.
Sound Management:
In extinguish(), if the audio stream should be stopped, consider adding checks to see if it is indeed playing, to avoid calls to stop an already stopped audio stream. Consider also adding conditions to prevent the same sound from overlapping unnecessarily.
Clear Comments:
Include comments in your code to clarify what functions are doing, especially in places where complex logic might confuse someone unfamiliar with the code.
Performance Optimization:
If the system grows larger over time and continues to manage many visual effects, consider optimizing the clear_spawned_effects() method to selectively clear effects based on their lifespan or conditions rather than clearing all.
Using Constants for Thresholds:
When checking conditions, defining constants for maximum values (like max_spawned_vfx) can improve readability and maintainability. This approach allows for easier changes to limits in one place.
Integration and Gameplay Aspects
Testing Interactions:
Make sure to test various scenarios where these elemental states interact. For instance, check how visual effects behave when switching between electrical and wet states.
Dynamic Gameplay Feedback:
Incorporating both audio and visual feedback when states change enhances player engagement. For example, different sound effects for electrifying or extinguishing can enrich the experience.
By refining these functions with the suggested improvements and testing their interactions extensively, you can enhance the game's mechanics around elemental properties and create an engaging, dynamic environment for players.