signal damage_received(damage_value:float)
signal object_exits_tree()
@export var cogito_name : String = self.name
var interaction_nodes : Array[Node]
var cogito_properties : CogitoProperties = null
var properties : int
Assistant
User
func _ready():
self.add_to_group("interactable")
self.add_to_group("Persist") #Adding object to group for persistence
find_interaction_nodes()
find_cogito_properties()
Future method to set object state when a scene state file is loaded.
func set_state():
#TODO: Find a way to possibly save health of health attribute.
find_cogito_properties()
pass
signal carry_state_changed(is_being_carried : bool)
signal thrown(impulse)
@export_group("Carriable Settings")
@export var pick_up_sound : AudioStream
@export var drop_sound : AudioStream
##Sets whether the object can be carried while wielding a weapon
@export var is_carryable_while_wielding : bool = false
Use this to adjust the carry position distance from the player. Per default it's the interaction raycast length. Negative values are closer, positive values are further away.
@export var carry_distance_offset : float = 0
Set if the object should not rotate when being carried. Usually true is preferred.
@export var lock_rotation_when_carried : bool = true
Sets how fast the carriable is being pulled towards the carrying position. The lower, the "floatier" it will feel.
@export var carrying_velocity_multiplier : float = 10
Sets how far away the carried object needs to be from the carry_position before it gets dropped.
@export var drop_distance : float = 1.5
Assistant
User
func _ready():
parent_object = get_parent()
if parent_object.has_signal("body_entered"):
parent_object.body_entered.connect(_on_body_entered) #Connecting to body entered signal
else:
CogitoGlobals.debug_log(true,"CarryableComponent.gd", parent_object.name + ": CarriableComponent needs to be child to a RigidBody3D to work.")
func interact(_player_interaction_component:PlayerInteractionComponent):
if !is_disabled:
carry(_player_interaction_component)
func carry(_player_interaction_component:PlayerInteractionComponent):
player_interaction_component = _player_interaction_component
if player_interaction_component.is_wielding and not is_carryable_while_wielding:
player_interaction_component.send_hint(null,"Can't carry an object while wielding.")
return
func rotate_object(_delta):
var input_dir
input_dir = Input.get_vector("left", "right", "forward", "back")
if input_dir.length() > 0:
var rotation_vector: Vector3 = Vector3(input_dir.y, input_dir.x, 0)
parent_object.global_rotate(rotation_vector, deg_to_rad(rotation_speed) )
func _on_body_entered(body):
if body.is_in_group("Player") and is_being_carried:
leave()
func _exit_tree():
if is_being_carried:
leave()
func hold():
if lock_rotation_when_carried:
parent_object.set_lock_rotation_enabled(true)
parent_object.freeze = false
player_interaction_component.start_carrying(self)
player_interaction_component.interaction_raycast.add_exception(parent_object)
# Play Pick up sound.
if pick_up_sound != null:
audio_stream_player_3d.stream = pick_up_sound
audio_stream_player_3d.play()
is_being_carried = true
carry_state_changed.emit(is_being_carried)
func leave():
# Making sure the player movement resumes when object is dropped while being rotated
if is_being_rotated:
player_interaction_component.player.is_movement_paused = false
@onready var label_title: Label = ReadableUi/Bindings/ScrollContainer/VBoxContainer/ReadableContent
@onready var readable_ui: Control = $ReadableUi
Assistant
User
extends ScrollContainer
var scrollable : Control
@export var animate = true
@export var transition_time = 0.2
@export var gamepad_scroll_speed : int = 5
@export var gamepad_scroll_deadzone : float = 0.1
var _last_input_event
var gamepad_scroll : float = 0
Your GDScript code looks like it's designed to modify a player's visibility attribute when they enter and exit an Area3D node in Godot. Below, I’ll give you a brief overview of how the code works, along with some potential improvements and considerations.
Code Explanation
Extending Area3D:
The script extends the Area3D class, meaning it is likely attached to an area node in a 3D scene.
Signal Methods:
_on_body_entered(body): This method is called when a body enters the area.
It checks if the body is part of the "Player" group. If it is, it increases the player's visibility attribute.
_on_body_exited(body): This method is called when a body exits the area.
Similar to the entry method, it checks for the "Player" group and decreases the visibility attribute.
Attribute Modification:
The methods call increase_attribute and decrease_attribute presumably defined on the player object to modify the visibility attribute.
Improvements and Considerations
Checking Signal Connections:
Ensure that the area is connected to the appropriate signals (body_entered and body_exited). You can connect these signals in the Godot editor or via code if you're not already doing so.
Graceful Handling of Missing Methods:
If increase_attribute or decrease_attribute is not defined on the player class, consider adding error handling or checks to avoid runtime errors.
if body.has_method("increase_attribute"):
body.increase_attribute("visibility", 1, ConsumableItemPD.ValueType.CURRENT)
else:
print("Player does not have increase_attribute method")
Visibility Range:
Be clear about what "visibility" means in your game context. Consider whether you may also want to set limits to prevent visibility from going below a minimum value.
Group Management:
Ensure your player is correctly added to the "Player" group inside the player script using:
add_to_group("Player")
Resource Management:
Depending on how you implement the visibility mechanic, be mindful of performance impacts, especially if many players can enter and exit this area frequently.
Example Full Script
Here’s the full script integrating these suggestions for clarity:
extends Area3D
func _ready():
connect("body_entered", self, "_on_body_entered")
connect("body_exited", self, "_on_body_exited")
func _on_body_entered(body):
if body.is_in_group("Player"):
if body.has_method("increase_attribute"):
body.increase_attribute("visibility", 1, ConsumableItemPD.ValueType.CURRENT)
else:
print("Player does not have increase_attribute method")
func _on_body_exited(body):
if body.is_in_group("Player"):
if body.has_method("decrease_attribute"):
body.decrease_attribute("visibility", 1)
else:
print("Player does not have decrease_attribute method")
Feel free to adjust according to the specifics of your game's requirements!
Your GDScript code looks like it is intended to enable or disable monitoring for a light zone (presumably an Area3D or a similar node) when a CogitoSwitch emits a "switched" signal. The structured approach is good, but let’s go through it and enhance it a bit for clarity and robustness.
Code Breakdown
Extending Node:
Your script is extending the basic Node class, which is a good choice if this script is meant to act as a controller or for attaching functionality to a node other than the Area3D.
Exporting Variables:
The switchable variable is marked with the @export keyword, allowing you to modify its value in the Godot editor.
Signal Connection:
The function _on_switched(is_on: bool) is designed to respond to a signal named "switched". When this signal is emitted, it checks if the light zone should be switchable.
Light Zone Monitoring:
If switchable is true, it gets the parent node (assumed to be an Area3D) and calls set_monitoring(is_on) on it to update its state.
Suggested Improvements
Signal Connection:
Ensure that _on_switched is connected to the switched signal from the CogitoSwitch. You can do this in the editor or programmatically in the _ready() function.
Error Handling:
You might want to add checks to verify that the parent node has a method called set_monitoring, to prevent run-time errors.
Documentation:
Adding brief comments/documentation can help others (or yourself in the future) understand what each part of the code is intended to do.
Enhanced Example
Here’s an example code with the above improvements:
extends Node
## Sets if parent lightzone should respond to CogitoSwitch "switched" signal.
@export var switchable: bool = true
func _ready():
# Ensure to connect the signal when the node is ready
if has_node("../CogitoSwitch"):
var cogito_switch = get_node("../CogitoSwitch") # adjust the path as needed
cogito_switch.connect("switched", self, "_on_switched")
else:
print("CogitoSwitch node not found in the expected location.")
## Connect to CogitoSwitch "switched" signal to enable or disable light zone monitoring
func _on_switched(is_on: bool):
if switchable:
var lightzone: Area3D = get_parent()
if lightzone and lightzone.has_method("set_monitoring"):
lightzone.set_monitoring(is_on)
else:
if lightzone:
print("Light zone does not have a set_monitoring method.")
else:
print("This node does not have a valid parent lightzone.")
Additional Considerations
Node Structure: Make sure that your node structure is correct. The path ../CogitoSwitch should point to the CogitoSwitch node relative to where this script is attached. Adjust the path as necessary.
Possible Method Signature Changes: If set_monitoring method accepts parameters other than just a Boolean, make sure to adjust the call accordingly.
Debugging Output: The added print statements will help in debugging if the connections or method calls fail, providing feedback on what's going wrong.
With these changes, your code should be more robust and easier to debug, while maintaining its primary functionality.
Your GDScript is setting up a new class named CogitoObject, which extends Node3D and includes various properties and signals. Below, I’ll break it down and provide suggestions for enhancing its usability and functionality.
Code Breakdown
Icon Declaration:
The @icon annotation allows your class to have a custom icon in the Godot editor, making it visually identifiable.
Class Definition:
The extends Node3D means this class is intended for 3D nodes, allowing it to work within the 3D scene context.
class_name CogitoObject registers the class so you can reference it more conveniently elsewhere in your project.
Signals:
signal damage_received(damage_value: float): This signal can be emitted when the object takes damage, passing the damage value as a parameter.
signal object_exits_tree(): This signal can be emitted when the object is removed from the scene tree.
Exported Variables:
@export var cogito_name: String = self.name: This is an exported variable initialized with the node's name, which can be modified through the Godot editor.
Member Variables:
var interaction_nodes: Array[Node]: This array will be used to store a list of interaction nodes related to the CogitoObject.
var cogito_properties: CogitoProperties = null: This variable is meant to hold properties associated with the object, if you have a custom CogitoProperties class defined elsewhere.
var properties: int: This integer could be used for various purposes, like tracking a specific state or property of the object.
Suggested Improvements
Initialization:
You might want to initialize interaction_nodes in _ready() or another initialization function. This ensures it starts as an empty array when your object is ready.
Signal Emission:
Consider implementing methods that emit the defined signals (damage_received and object_exits_tree) when appropriate, allowing other parts of your code to respond appropriately.
Handling cogito_properties:
If CogitoProperties is supposed to be a data structure containing various properties, you might want to instantiate it or define it if it’s not already done elsewhere.
Optional Default Logic:
Override methods like _process(delta) or _physics_process(delta) if you want to define behavior for every frame.
Example Enhanced Code
Here's an example of your original code with some enhancements:
@icon("res://addons/cogito/Assets/Graphics/Editor/Icon_CogitoObject.svg")
extends Node3D
class_name CogitoObject
signal damage_received(damage_value: float)
signal object_exits_tree()
@export var cogito_name: String = self.name
var interaction_nodes: Array[Node] = []
var cogito_properties: CogitoProperties = null
var properties: int = 0
# Optional: Add this function to handle taking damage
func take_damage(damage_value: float):
# Emit the damage_received signal with the damage value
emit_signal("damage_received", damage_value)
# Logic to handle damage, e.g., reduce health, etc.
# Optional: Connect this function to the exit signal
func _on_exit_tree():
emit_signal("object_exits_tree")
func _ready():
# Initialization logic
interaction_nodes = []
# Additional setup for properties
if cogito_properties == null:
cogito_properties = CogitoProperties() # Initialize if needed
# Connect the exit tree signal
connect("tree_exited", self, "_on_exit_tree")
Additional Considerations
Error Handling: Depending on how you use CogitoProperties, make sure it’s the right type or check if it needs initialization with certain parameters.
Signal Connections: If you have other scripts or nodes responding to the emitted signals, make sure they are connected to these signals correctly.
Comments and Documentation: Adding comments and documentation will help maintain this code. It can also assist other developers (or yourself later) in understanding the intent behind specific implementations.
These improvements will not only maintain the features of your original code but will also enhance its functionality and robustness in managing the interaction of the CogitoObject within the Godot scene.
func find_interaction_nodes():
interaction_nodes = find_children("","InteractionComponent",true) #Grabs all attached interaction components
func find_cogito_properties():
var property_nodes = find_children("","CogitoProperties",true) #Grabs all attached property components
if property_nodes:
cogito_properties = property_nodes[0]
}
# If the node is a RigidBody3D, then save the physics properties of it
var rigid_body = find_rigid_body()
if rigid_body:
node_data["linear_velocity_x"] = rigid_body.linear_velocity.x
node_data["linear_velocity_y"] = rigid_body.linear_velocity.y
node_data["linear_velocity_z"] = rigid_body.linear_velocity.z
node_data["angular_velocity_x"] = rigid_body.angular_velocity.x
node_data["angular_velocity_y"] = rigid_body.angular_velocity.y
node_data["angular_velocity_z"] = rigid_body.angular_velocity.z
return node_data
func find_rigid_body() -> RigidBody3D:
var current = self
while current:
if current is RigidBody3D:
return current as RigidBody3D
current = current.get_parent()
return null
func _on_body_entered(body: Node) -> void:
# Using this check to only call interactions on other Cogito Objects. #TODO: could be a better check...
if body.has_method("save") and cogito_properties:
cogito_properties.start_reaction_threshold_timer(body)
func _on_body_exited(body: Node) -> void:
# Using this check to only call interactions on other Cogito Objects. #TODO: could be a better check...
if body.has_method("save") and cogito_properties:
cogito_properties.check_for_reaction_timer_interrupt(body)
Your GDScript code provides a robust framework for managing the lifecycle of a CogitoObject in Godot, including methods for setting its state, finding children nodes, handling persistence, and responding to interactions. Below is a breakdown of the code with explanations, followed by suggestions for improvement where applicable.
Code Breakdown
Inheritance and Initialization:
The _ready() method initializes the object by adding it to groups named "interactable" and "Persist"—useful for categorizing and managing object types in the scene. It then calls find_interaction_nodes() and find_cogito_properties() to set up interaction and property components.
State Management:
The set_state() method hints that you'll need to implement functionality to possibly save and restore the object's health state, linked to a health attribute.
Finding Children Nodes:
find_interaction_nodes(): This method locates all children nodes of type InteractionComponent and stores them in interaction_nodes.
find_cogito_properties(): Similar but for CogitoProperties, assigning the first found instance to cogito_properties.
Saving State:
The save() method collects various positional, rotational, and potentially physical properties of the object—including interactions with RigidBody3D, if applicable. This data is returned in a dictionary format.
RigidBody3D Lookup:
find_rigid_body(): This utility method traverses up the hierarchy to find the nearest parent node of type RigidBody3D. It's a good way to ensure you get the correct physical properties without needing to tightly couple the object to RigidBody3D.
Interaction Handling:
The methods _on_body_entered(body) and _on_body_exited(body) respond to collision events with other nodes (like other CogitoObjects), invoking methods from cogito_properties to manage interaction timers based on the presence of a body.
Clean Exit:
In _exit_tree(), the object_exits_tree signal is emitted to inform other systems that this object is being removed from the scene.
Suggested Improvements
State Saving Enhancements:
In the save() method, you may want to consider serializing and saving more attributes (like health, inventory, etc.), making it easier to restore the object’s complete state.
Robustness in Finding Nodes:
In find_cogito_properties(), you may want to ensure that there aren’t multiple CogitoProperties and if there are, how you wish to handle them (e.g., take the first one or throw an error).
Signal Management:
Ensure signals like object_exits_tree are connected properly to any listeners in other parts of your game, and consider adding other signals for additional lifecycle events if needed.
Improve Interaction Checks:
For the checks in _on_body_entered and _on_body_exited, consider establishing clear interface contracts (possibly via a base class or interface) so that you can check for more specific interactions rather than just the presence of a method.
Processing and Physics Handling:
If your objects may need to perform periodic updates (like checking for state changes or animation updates), consider overriding the _process(delta) or _physics_process(delta) functions.
Example of an Enhanced Save Method
Here’s an example of how you might further enhance the save() method if you had a health property:
func save():
var node_data = {
"filename": get_scene_file_path(),
"parent": get_parent().get_path(),
"interaction_nodes": interaction_nodes,
"pos": position,
"rot": rotation,
"health": cogito_properties.health, # Assuming you have a health property to save
}
# Include physics properties if applicable
var rigid_body = find_rigid_body()
if rigid_body:
node_data["linear_velocity"] = rigid_body.linear_velocity
node_data["angular_velocity"] = rigid_body.angular_velocity
return node_data
Final Considerations
Documentation: Add comments to complex logic or methods. This will help future developers (or yourself) understand the purpose of various parts of your code.
Testing in Godot: Make sure to rigorously test the interactions and state management in various in-game scenarios to identify any edge cases or unhandled states.
Performance Considerations: Consider the performance implications of searching for nodes and the data structures you utilize; make sure they fit your game's expected scale.
This approach should provide a more complete and usable structure for your CogitoObject class while maintaining flexibility for future enhancements.
Sets if object can be rotated while being carried
@export var enable_manual_rotating : bool = true
How fast the object rotates (in degrees per second)
@export var rotation_speed : float = 2.0
@onready var audio_stream_player_3d = $AudioStreamPlayer3D
@onready var camera : Camera3D = get_viewport().get_camera_3d()
var parent_object
var is_being_carried : bool
var is_being_rotated : bool = false
var player_interaction_component : PlayerInteractionComponent
var carry_position : Vector3 #Position the carria
Your GDScript code defines a CogitoCarryableComponent, which extends InteractionComponent and provides functionality for carrying and manipulating objects in a 3D environment in Godot. Below, I'll provide a breakdown of the code, explain its structure, and offer suggestions to improve its functionality and organization.
This line declares that your component is a subclass of InteractionComponent, allowing it to inherit behavior from the base class.
Signals:
signal carry_state_changed(is_being_carried: bool)
signal thrown(impulse)
carry_state_changed: This signal notifies when the carrying state changes, allowing other components (or systems) to respond accordingly.
thrown: This signal indicates that the object has been thrown, carrying an impulse which could be used to determine the throw direction and force.
Export Variables:
The sections with @export keywords allow you to customize settings in the Godot editor, making the component easier to configure without needing to write additional code.
@export_group("Carriable Settings")
@export var pick_up_sound: AudioStream
@export var drop_sound: AudioStream
@export var is_carryable_while_wielding: bool = false
@export var carry_distance_offset: float = 0
@export var lock_rotation_when_carried: bool = true
@export var carrying_velocity_multiplier: float = 10
@export var drop_distance: float = 1.5
@export var enable_manual_rotating: bool = true
@export var rotation_speed: float = 2.0
Each variable has a clear purpose related to the carrying mechanics, like audio cues, carrying behavior, and controls.
Node References:
@onready var audio_stream_player_3d = $AudioStreamPlayer3D
@onready var camera: Camera3D = get_viewport().get_camera_3d()
@onready initializes these variables when the node is ready, ensuring they reference the correct nodes in your scene tree.
Member Variables:
var parent_object
var is_being_carried: bool
var is_being_rotated: bool = false
var player_interaction_component: PlayerInteractionComponent
var carry_position: Vector3
These variables store the state and necessary references for the carrying functionality, such as whether the object is currently being carried or rotated.
Suggested Improvements
Initialization of parent_object and is_being_carried:
You should initialize is_being_carried to false to avoid unintentionally invoking behavior based on undefined values. Also, you might want to make sure parent_object is set appropriately.
func _ready():
is_being_carried = false
parent_object = get_parent() # Example: set the parent object if needed.
player_interaction_component = find_parent_player_interaction_component()
Define Carry Mechanics:
You’ll need methods to manage picking up, dropping, and possibly throwing the carried object. Key methods could include pick_up(), drop(), and throw().
func pick_up():
is_being_carried = true
emit_signal("carry_state_changed", true)
audio_stream_player_3d.stream = pick_up_sound
audio_stream_player_3d.play()
# Additional logic to position the object near the carrying player's hand.
func drop():
is_being_carried = false
emit_signal("carry_state_changed", false)
audio_stream_player_3d.stream = drop_sound
audio_stream_player_3d.play()
# Logic for dropping the object at the current location.
func throw(impulse: Vector3):
drop() # Make sure to drop before throwing
emit_signal("thrown", impulse) # Emit the thrown signal
# Logic for applying impulse to the object if it has a RigidBody.
Manual Rotation Functionality:
If enable_manual_rotating is true, provide a method to allow players to rotate the object while it’s being carried based on player input.
func _process(delta: float):
if is_being_carried and is_being_rotated:
if enable_manual_rotating:
var rotation_input = Vector3() # Set this to the player's input
rotation_input.y += rotation_speed * delta
# Apply rotation to the object based on rotation_input
Handling Impulse for Thrown Objects:
When a carryable object is thrown, make sure to apply the impulse properly, especially if it inherits from RigidBody3D.
Documentation and Comments:
Consider adding comments throughout the code to thoroughly document the purpose and expected behavior of different methods and properties.
Final Considerations
Creating a carryable component in Godot can be complex, especially when considering user interactions and physics. Ensure you thoroughly test how the interaction feels in the game, and make adjustments based on feedback to improve usability and gameplay experience.
By implementing the above suggestions, you should have a more robust and functional CogitoCarryableComponent that enhances player interactions with objects in your game.
if enable_manual_rotating:
if enable_manual_rotating and Input.is_action_pressed("action_secondary"):
player_interaction_component.player.is_movement_paused = true
is_being_rotated = true
rotate_object(_delta)
# Resume player movement when input action is released
if is_being_rotated and Input.is_action_just_released("action_secondary"):
player_interaction_component.player.is_movement_paused = false
if(carry_position-parent_object.global_position).length() >= drop_distance:
leave()
Your GDScript implementation for the CogitoCarryableComponent provides functionality for picking up and carrying an object in a 3D Godot game. This functionality includes checking if the carrying action is valid, moving the object towards the player, and allowing for smooth rotations. Below is a breakdown of your code with some suggestions for improvements and best practices.
Code Breakdown
Initialization:
func _ready():
parent_object = get_parent()
if parent_object.has_signal("body_entered"):
parent_object.body_entered.connect(_on_body_entered) # Connecting to body entered signal
else:
CogitoGlobals.debug_log(true, "CarryableComponent.gd", parent_object.name + ": CarryableComponent needs to be child to a RigidBody3D to work.")
In _ready(), the script checks if its parent object has the body_entered signal. If it does, it connects _on_body_entered, allowing responses to collision events. If not, it logs a message indicating the requirement.
Interaction Handling:
func interact(_player_interaction_component: PlayerInteractionComponent):
if !is_disabled:
carry(_player_interaction_component)
The interact method is responsible for handling player interactions and calling the carry method if the component is not disabled.
Carrying Logic:
func carry(_player_interaction_component: PlayerInteractionComponent):
player_interaction_component = _player_interaction_component
if player_interaction_component.is_wielding and not is_carryable_while_wielding:
player_interaction_component.send_hint(null, "Can't carry an object while wielding.")
return
if is_being_carried:
leave()
else:
hold()
This method checks whether the object can be carried based on the player's current state (e.g., wielding a weapon) and either holds the object or makes it leave.
Physics Update:
func _physics_process(_delta):
if is_being_carried:
carry_position = player_interaction_component.get_carryable_destination_point(carry_distance_offset)
parent_object.set_linear_velocity((carry_position - parent_object.global_position) * carrying_velocity_multiplier)
if enable_manual_rotating and Input.is_action_pressed("action_secondary"):
player_interaction_component.player.is_movement_paused = true
is_being_rotated = true
rotate_object(_delta)
if is_being_rotated and Input.is_action_just_released("action_secondary"):
player_interaction_component.player.is_movement_paused = false
if (carry_position - parent_object.global_position).length() >= drop_distance:
leave()
In the physics process, if the object is being carried, it calculates the target carry_position and moves the object towards it by setting its linear_velocity. It also handles rotation when a secondary action is pressed and checks if the object needs to be dropped if it goes out of range.
Suggested Improvements
Clarifying leave() and hold():
Ensure the leave() and hold() methods are implemented properly and include necessary actions such as resetting state, playing sounds, etc.
func leave():
is_being_carried = false
player_interaction_component.player.is_movement_paused = false
parent_object.set_linear_velocity(Vector3.ZERO) # Stop movement logic
emit_signal("carry_state_changed", false)
# Additional cleanup or sound effects
func hold():
is_being_carried = true
emit_signal("carry_state_changed", true)
# Logic to position object correctly (e.g., play sound)
audio_stream_player_3d.stream = pick_up_sound
audio_stream_player_3d.play()
Consolidate Velocity Movement:
Instead of calculating the target position and applying velocity each frame, consider applying forces for a more physically accurate representation, especially if using RigidBody3D.
Rotation During Carry:
Make sure the rotate_object method properly handles the rotation logic. Ensure the rotation is smooth and respects the rotation_speed variable.
func rotate_object(_delta):
var rotation_input = Vector3() # Determine axis based on user input
# Rotate based on input and rotation speed
parent_object.rotate_y(rotation_input.y * rotation_speed * _delta)
Use Strong Naming Conventions:
Ensure variable and method names are clear and consistent. For instance, instead of player_interaction_component, consider shorter aliases or descriptive names.
Error Handling:
Implement error handling or fallback mechanisms, particularly in methods that manipulate physics or interact with other game components. Consider logging if dependent components (like PlayerInteractionComponent) aren't set.
Final Considerations
Testing and Adjustment: Rigorously test how the carrying system feels in gameplay. Ensure that object interactions feel responsive and intuitive.
Documentation: Continue commenting your code. Good documentation helps maintain the codebase and onboard new developers easily.
Performance Considerations: Monitor performance, and ensure that calculating linear velocities and handling inputs is efficient, especially in complex scenes or with multiple carryable objects.
By following these enhancements, your CogitoCarryableComponent can be made more robust, intuitive, and responsive to player interactions, improving the overall gameplay experience.
if lock_rotation_when_carried:
parent_object.set_lock_rotation_enabled(false)
if player_interaction_component and is_instance_valid(player_interaction_component):
player_interaction_component.stop_carrying()
player_interaction_component.interaction_raycast.remove_exception(parent_object)
is_being_carried = false
carry_state_changed.emit(is_being_carried)
func throw(power):
leave()
if drop_sound:
audio_stream_player_3d.stream = drop_sound
audio_stream_player_3d.play()
var impulse = player_interaction_component.Get_Look_Direction() * power
parent_object.apply_central_impulse(impulse)
thrown.emit(impulse)
Your GDScript code for the CogitoCarryableComponent outlines methods for handling object rotation, carrying, throwing, and handling interactions with the player. Here’s an overview of the main features, along with some suggestions for optimizing and enhancing your implementation.
Code Breakdown
Rotating the Object:
func rotate_object(_delta):
var input_dir
input_dir = Input.get_vector("left", "right", "forward", "back")
if input_dir.length() > 0:
var rotation_vector: Vector3 = Vector3(input_dir.y, input_dir.x, 0)
parent_object.global_rotate(rotation_vector, deg_to_rad(rotation_speed))
This method retrieves directional input from the player and uses it to rotate the parent object. The rotation is calculated using the input direction's x and y components.
Handling Collision with Player:
func _on_body_entered(body):
if body.is_in_group("Player") and is_being_carried:
leave()
Upon collision with a player, if the object is being carried, it triggers the leave() method to drop the object.
Cleaning Up on Exit:
func _exit_tree():
if is_being_carried:
leave()
This method ensures that if the node is removed from the scene tree while being carried, the carrying state is reset.
Holding the Object:
func hold():
if lock_rotation_when_carried:
parent_object.set_lock_rotation_enabled(true)
parent_object.freeze = false
player_interaction_component.start_carrying(self)
player_interaction_component.interaction_raycast.add_exception(parent_object)
# Play Pick up sound.
if pick_up_sound != null:
audio_stream_player_3d.stream = pick_up_sound
audio_stream_player_3d.play()
is_being_carried = true
carry_state_changed.emit(is_being_carried)
The hold() method manages the logic for starting the carry. It plays a sound, updates the carrying state, and ensures the object’s rotations can be locked if specified.
Leaving the Carry State:
func leave():
# Making sure the player movement resumes when the object is dropped while being rotated
if is_being_rotated:
player_interaction_component.player.is_movement_paused = false
if lock_rotation_when_carried:
parent_object.set_lock_rotation_enabled(false)
if player_interaction_component and is_instance_valid(player_interaction_component):
player_interaction_component.stop_carrying()
player_interaction_component.interaction_raycast.remove_exception(parent_object)
is_being_carried = false
carry_state_changed.emit(is_being_carried)
The leave() method resets relevant states when the object is dropped or left. It ensures the player can move again and updates the state of the player_interaction_component.
Throwing the Object:
func throw(power):
leave()
if drop_sound:
audio_stream_player_3d.stream = drop_sound
audio_stream_player_3d.play()
var impulse = player_interaction_component.Get_Look_Direction() * power
parent_object.apply_central_impulse(impulse)
thrown.emit(impulse)
The throw() method handles dropping the object and applying an impulse based on the player's look direction and a specified power, allowing for a dynamic throw mechanic.
Suggested Improvements
Input Handling:
Ensure that the input method (Input.get_vector()) refers to correctly set actions in the InputMap. You could combine directional input checking with rotation by simplifying how directions are handled (like using right for x and up for y).
Rotation Logic:
Modify the rotation process to prevent gimbal lock by using quaternion rotation if you are rotating objects in more complex scenarios.
func rotate_object(_delta):
var input_dir = Input.get_vector("left", "right", "forward", "back")
if input_dir.length() > 0:
var rotation_amount = input_dir.y * rotation_speed * _delta
parent_object.rotate_y(deg_to_rad(rotation_amount))
Play Sounds:
Add checks to ensure that sounds are not played if they are null. If the sound should always play (even if it is null), you could fallback to a default sound or log a warning.
Use of Physics for Better Realism:
Optionally use apply_impulse instead of apply_central_impulse for more control over the direction and force, especially if you want to provide more nuanced behaviors based on object states.
Avoid Global State Issues:
In leave(), ensure that you're resetting the state as needed. Instead of relying on is_being_rotated, it might help to track whether the object was rotated before the drop occurred.
Improve Logging and Feedback:
Expand upon your debug_log system to include helpful output when actions occur (like successful lifts, drops, and throws). Logging will help with understanding issues during development.
Refactor Impulse Calculation for Clarity:
Create a utility function to calculate the impulse vector to avoid repetition and improve the readability of your code.
Final Considerations
Testing: Thoroughly test how the behaviors feel in gameplay. It’s essential to ensure that actions like carrying, rotating, and throwing are intuitive.
Documentation: Continue to comment and document your code to clarify what each section does, which aids in both maintenance and team collaboration.
Performance: Monitor performance during gameplay, especially with active objects and physics calculations, to ensure there are no frame rate drops or slowdowns.
By implementing these improvements, your CogitoCarryableComponent will not only function better but also provide a more engaging experience for players.
if not _player_interaction_component.get_parent().inventory_data.pick_up_slot_data(slot_data):
return
# Update wieldable UI if we have picked up ammo for current wieldable
# TODO: Possibly replace with a better solution, maybe by signaling the change
# to the UI instead of having the PlayerInteractionComponent doing it.
if _player_interaction_component.is_wielding:
var is_ammo: bool = "reload_amount" in slot_data.inventory_item
var is_current_ammo: bool = _player_interaction_component.equipped_wieldable_item.ammo_item_name == slot_data.inventory_item.name
if is_ammo and is_current_ammo:
_player_interaction_component.equipped_wieldable_item.update_wieldable_data(_player_interaction_component)
_player_interaction_component.send_hint(slot_data.inventory_item.icon, slot_data.inventory_item.name + " added to inventory.")
was_interacted_with.emit(interaction_text, input_map_action)
Audio.play_sound(slot_data.inventory_item.sound_pickup)
self.get_parent().queue_free()
func get_item_type() -> int:
if slot_data and slot_data.inventory_item:
return slot_data.inventory_item.item_type
else:
return -1
Your GDScript code for the PickupComponent is designed to allow objects in your Godot project to be picked up by a player, specifically by managing the inventory and handling inventory-related interactions. Below, I'll provide a breakdown of your code, as well as suggestions for improvements.
This declares the class PickupComponent, which extends InteractionComponent. This means PickupComponent inherits any methods and properties defined in InteractionComponent.
Exported Variables:
@export var slot_data: InventorySlotPD
This line allows you to set the variable slot_data in the Godot editor, which presumably contains information about the item being picked up (like its type, quantity, etc.).
Player Interaction Component:
var player_interaction_component
A reference to the player’s interaction component, which allows the pickup component to interact with the player's inventory and state.
Interaction Method:
func interact(_player_interaction_component: PlayerInteractionComponent):
if !is_disabled:
pick_up(_player_interaction_component)
This method is called to interact with the component. It checks if the component is enabled and attempts to pick it up.
Pick Up Method:
func pick_up(_player_interaction_component: PlayerInteractionComponent):
### Currency Item handling
if slot_data.inventory_item is CurrencyItemPD and slot_data.inventory_item.add_on_pickup:
if slot_data.inventory_item.use(_player_interaction_component.get_parent()):
Audio.play_sound(slot_data.inventory_item.sound_pickup)
was_interacted_with.emit(interaction_text, input_map_action)
self.get_parent().queue_free()
return
else:
_player_interaction_component.send_hint(slot_data.inventory_item.icon, slot_data.inventory_item.name + " couldn't be picked up.")
return
This method manages the logic for picking up items. It first checks if the item is a currency item with a special pickup behavior. If so, it attempts to use the currency, playing a sound and removing the item if successful. If not, it sends a hint message.
Then, it attempts to add the item to the player’s inventory through _player_interaction_component.get_parent().inventory_data.pick_up_slot_data(slot_data).
If the player is currently wielding an item, it updates the UI details of that item if the new item is relevant.
Get Item Type Method:
func get_item_type() -> int:
if slot_data and slot_data.inventory_item:
return slot_data.inventory_item.item_type
else:
return -1
This method checks if the slot_data and inventory_item are valid, returning the item's type or -1 if not.
Suggested Improvements
Better Event Handling:
During interactions, consider using signals to notify other components when an item is picked up rather than calling methods directly. This decouples the components and makes your code more maintainable.
Refactor Usability Alerts:
The function _player_interaction_component.send_hint(...) is called several times; if this method becomes more complex, consider refactoring it into a utility method to ensure consistency and maintainability.
Check for Valid Items:
Before checking for CurrencyItemPD, it might be prudent to check if slot_data.inventory_item is valid to prevent potential errors:
if slot_data and slot_data.inventory_item:
if slot_data.inventory_item is CurrencyItemPD:
Player Feedback:
You might want to improve player feedback further; for instance, you could implement a method to play hints and popup notifications in the UI instead of just through the console.
Expand on Inventory Management:
The current implementation assumes that inventory management is always successful. Consider providing a feedback mechanism that indicates whether the action was successful or not, including managing overflow or item capacity.
Centralize Sound Management:
Consider centralizing your sound management using a singleton or dedicated audio manager for more control, such as managing overlapping sounds or playing sounds from many different components at once.
Clarify Logic for Wieldable Items:
You mention a "better solution" for updating the UI regarding ammo. This might benefit from directly emitting signals from the PickupComponent to update the UI, preserving a single responsibility for each component.
Example of Improved Code
Here's an example of an updated pick_up method, implementing some of the suggestions:
func pick_up(_player_interaction_component: PlayerInteractionComponent):
if not slot_data or not slot_data.inventory_item:
_player_interaction_component.send_hint(null, "No item to pick up.")
return
# Currency Item handling
if slot_data.inventory_item is CurrencyItemPD:
if slot_data.inventory_item.add_on_pickup:
if slot_data.inventory_item.use(_player_interaction_component.get_parent()):
Audio.play_sound(slot_data.inventory_item.sound_pickup)
was_interacted_with.emit(interaction_text, input_map_action)
self.queue_free() # Queue free avoids calling 'get_parent()' again
return
else:
_player_interaction_component.send_hint(slot_data.inventory_item.icon, "{0} couldn't be picked up.".format(slot_data.inventory_item.name))
return
if not _player_interaction_component.get_parent().inventory_data.pick_up_slot_data(slot_data):
_player_interaction_component.send_hint(slot_data.inventory_item.icon, "Inventory full.")
# Update wieldable UI if we have picked up ammo for current wieldable
if _player_interaction_component.is_wielding:
var is_ammo: bool = "reload_amount" in slot_data.inventory_item
var is_current_ammo: bool = _player_interaction_component.equipped_wieldable_item.ammo_item_name == slot_data.inventory_item.name
if is_ammo and is_current_ammo:
_player_interaction_component.equipped_wieldable_item.update_wieldable_data(_player_interaction_component)
_player_interaction_component.send_hint(slot_data.inventory_item.icon, "{0} added to inventory.".format(slot_data.inventory_item.name))
Audio.play_sound(slot_data.inventory_item.sound_pickup)
self.queue_free()
Final Considerations
Thorough Testing: Ensure that the pick-up logic works as intended. Execute edge cases like inventory full scenarios and handling multiple interactions to verify that your code is robust.
Documentation: Maintain a good level of documentation within your codebase so future developers (or you) can quickly understand the functionality during maintenance or expansion.
By implementing these improvements, your PickupComponent can become more robust, user-friendly, and easier to maintain, contributing positively to the overall quality of your game.
Your ReadableComponent script for Godot is designed to allow players to read in-game text, like books or notes, within the context of your game. It manages UI interactions, including displaying rich or regular text and handling the player's interactions. Below, I’ll break down your code and provide suggestions for possible improvements and enhancements for better usability and maintainability.
This defines the ReadableComponent class, extending InteractionComponent, so it inherits interaction capabilities.
Signals:
signal has_been_read
This signal is emitted when the player reads the text, allowing other components to react accordingly.
Node References:
@onready var label_title: Label = $ReadableUi/Bindings/ScrollContainer/VBoxContainer/ReadableTitle
@onready var label_content: RichTextLabel = $ReadableUi/Bindings/ScrollContainer/VBoxContainer/ReadableContent
@onready var readable_ui: Control = $ReadableUi
@onready variables are initialized when the node is ready, avoiding issues related to node availability during initialization.
Exported Variables:
@export_group("Readable Settings")
@export var interact_sound : AudioStream
@export var readable_title : String
@export_multiline var readable_content : String
@export var rich_text : bool
These variables are configurable in the Godot editor. It allows you to set properties like the title and content of the readable object, as well as sound for interactions.
This method is called when the player interacts with the component. It plays the interaction sound and toggles the readable UI on or off.
Opening and Closing Logic:
func open(_player_interaction_component: PlayerInteractionComponent):
_player_interaction_component.get_parent().toggled_interface.emit(true)
_player_interaction_component.get_parent().menu_pressed.connect(close) #Connecting input action menu to close function.
readable_ui.show()
has_been_read.emit()
is_open = true
func close(_player_interaction_component: PlayerInteractionComponent):
readable_ui.hide()
_player_interaction_component.get_parent().menu_pressed.disconnect(close)
is_open = false
_player_interaction_component.get_parent().toggled_interface.emit(false)
The open method displays the readable UI and connects menu input to the close method. The close method hides the UI and disconnects from the menu input.
Suggested Improvements
Error Handling:
Add checks for the availability of nodes before calling methods on them to avoid potential runtime errors.
func interact(_player_interaction_component: PlayerInteractionComponent):
if not _player_interaction_component.get_parent():
print("Player interaction component's parent is not valid.")
return
Centralized Sound Management:
Instead of playing sounds directly within the interact method, consider using a dedicated audio manager to maintain and manage audio resources throughout your game. This will keep the audio handling more flexible.
Improved Input Handling:
Instead of connecting the menu_pressed signal directly in open, consider using an input handling method that better organizes input actions. This way, you can manage it dynamically, allowing for more complex interactions down the line.
Consider UI Scaling:
If the UI is intended to meet different resolutions or screen sizes, ensure that your control nodes are appropriately set up to handle dynamic UI scaling or adjustments.
Use Enum for Read States:
If the readable UI may have more states in the future, consider using an enum to define the states of the interface (e.g., CLOSED, OPEN, READING) instead of using a boolean.
Refine Rich Text Logic:
Ensure that the logic around rich_text is robust. If you later allow multiline support, be mindful of how the text is broken down and whether any formatting is lost or ignored.
Additional Actions on Close:
Assuming that closing may lead to additional actions (like changing the state of the player or sending analytics), consider adding comments or code in the close function depending on the intended functionality.
Example Improved Code
Here's an example of the refined ReadableComponent code, integrating some of the suggestions:
extends InteractionComponent
class_name ReadableComponent
signal has_been_read
@onready var label_title: Label = $ReadableUi/Bindings/ScrollContainer/VBoxContainer/ReadableTitle
@onready var label_content: RichTextLabel = $ReadableUi/Bindings/ScrollContainer/VBoxContainer/ReadableContent
@onready var readable_ui: Control = $ReadableUi
@export_group("Readable Settings")
@export var interact_sound: AudioStream
@export var readable_title: String
@export_multiline var readable_content: String
@export var rich_text: bool
var is_open: bool
func _ready():
readable_ui.hide()
is_open = false
label_title.text = readable_title
if rich_text:
label_content.bbcode_enabled = true
label_content.bbcode_text = readable_content
else:
label_content.text = readable_content
func interact(_player_interaction_component: PlayerInteractionComponent):
if not is_instance_valid(_player_interaction_component):
print("Invalid player interaction component")
return
Audio.play_sound_3d(interact_sound).global_position = self.global_position
if is_open:
close(_player_interaction_component)
else:
open(_player_interaction_component)
func open(_player_interaction_component: PlayerInteractionComponent):
var parent = _player_interaction_component.get_parent()
if not parent:
print("Parent of player interaction component is invalid.")
return
parent.toggled_interface.emit(true)
parent.menu_pressed.connect(close)
readable_ui.show()
has_been_read.emit()
is_open = true
func close(_player_interaction_component: PlayerInteractionComponent):
readable_ui.hide()
var parent = _player_interaction_component.get_parent()
if parent and parent.menu_pressed.is_connected(close):
parent.menu_pressed.disconnect(close)
is_open = false
parent.toggled_interface.emit(false)
Final Considerations
Testing: Ensure proper testing occurs with various players interacting with the readable components to handle edge cases and verify proper functionality.
Documentation: Continue to document your code effectively to make future references easier for you and others who interact with your codebase.
By implementing these improvements, your ReadableComponent will become cleaner and better structured, enhancing both performance and maintainability within your larger game context.
Your GDScript code defines a custom ScrollContainer, allowing users to scroll through UI elements using both mouse controls and gamepad input. The code effectively integrates animation for smooth scrolling and handles focus changes when different UI elements receive focus. Below is a breakdown of your existing code, along with suggestions for potential improvements.
Code Breakdown
Class Declaration:
extends ScrollContainer
This script extends the ScrollContainer class, meaning it inherits all properties and methods of the ScrollContainer, allowing it to be used as a scrollable UI element.
Variables:
var scrollable: Control
@export var animate = true
@export var transition_time = 0.2
@export var gamepad_scroll_speed: int = 5
@export var gamepad_scroll_deadzone: float = 0.1
var _last_input_event
var gamepad_scroll: float = 0
The script defines the components and properties of the scrollable container, including options for animation and gamepad scrolling.
In the _ready() function, it initializes the scrollable variable to the first child of the ScrollContainer, setting the focus change listener for GUI elements.
This helper function computes the position of one control relative to another by subtracting their global positions.
Focus Change Handling:
func focus_changed(focus: Control):
if _last_input_event is InputEventMouseButton:
return
var scroll_destination = _get_position_relative_to_control(scrollable, focus).y - get_rect().size.y / 2
if animate:
var tween = create_tween().set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_OUT)
tween.tween_property(self, "scroll_vertical", scroll_destination, transition_time)
else:
scroll_vertical = scroll_destination
When focus changes, it computes the scroll destination based on the focused control's position. It either animates the scrolling to that position or jumps immediately to it.
Input Handling:
func _input(event):
_last_input_event = event
# Checking Analog stick input for mouse look
if event is InputEventJoypadMotion:
if event.get_axis() == 3:
gamepad_scroll = event.get_axis_value()
The _input() function tracks the last input event and records the value from the gamepad’s analog stick (specifically axis 3).
In the _process() method, if the gamepad's scroll value exceeds the defined dead zone, it updates the vertical scroll position based on the gamepad's input.
Suggested Improvements
Handling Mouse and Gamepad Input Separately:
Consider organizing how you handle mouse and gamepad input to avoid conflicts. Group checks for different types of inputs, and ensure they operate without interfering with one another.
Scoped Variables:
Introduce a scope for any input detection or movement behavior to handle focus changes more intuitively.
Dynamic Scroll Speed:
Make gamepad_scroll_speed adjustable during gameplay to allow for different sensitivity settings based on player preference. You can implement this through a settings menu.
Enhanced User Feedback:
Consider adding a small bounce effect at the edges of the scroll area to give users feedback when they try to scroll past the available content.
Input Mapping:
Ensure that your input mapping for gamepad axes is clearly defined within the InputMap settings of Godot so that you can capture button presses consistently across various devices.
Smoothing Scroll Behavior:
Smooth out the scrolling behavior even further by adding friction or easing effects upon release if scrolling momentum is detected.
Vertical Scroll Direction:
Allow for the option to toggle or invert the scrolling direction depending on player preference.
Commenting and Documentation:
Add comments throughout the code to clarify the intent of key sections. This improves maintainability and aids others (or your future self) in understanding the functionality.
Example of Improved Code
Here’s an improved version of your script, incorporating some suggestions:
extends ScrollContainer
var scrollable: Control
@export var animate: bool = true
@export var transition_time: float = 0.2
@export var gamepad_scroll_speed: int = 5
@export var gamepad_scroll_deadzone: float = 0.1
var _last_input_event
var gamepad_scroll: float = 0
func _ready():
scrollable = get_child(0)
get_viewport().gui_focus_changed.connect(focus_changed)
func _get_position_relative_to_control(a: Control, b: Control) -> Vector2:
return b.get_global_rect().position - a.get_global_rect().position
func focus_changed(focus: Control):
if _last_input_event is InputEventMouseButton:
return
var scroll_destination = _get_position_relative_to_control(scrollable, focus).y - get_rect().size.y / 2
if animate:
var tween = create_tween().set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_OUT)
tween.tween_property(self, "scroll_vertical", scroll_destination, transition_time)
else:
scroll_vertical = scroll_destination
func _input(event):
_last_input_event = event
if event is InputEventJoypadMotion and event.get_axis() == 3:
gamepad_scroll = event.get_axis_value()
func _process(delta: float) -> void:
if abs(gamepad_scroll) > gamepad_scroll_deadzone:
scroll_vertical += gamepad_scroll_speed * gamepad_scroll * delta
Final Considerations
Thorough Testing: Make sure to playtest with various input setups, including mouse and gamepad configurations, to assess effectiveness.
Flexibility for Future Features: Designing your code with potential future enhancements in mind (like additional settings or UI components) will make it easier to build on later without major rewrites.
By applying these enhancements, your ScrollContainer will not only function more effectively but will also provide a better user experience as part of your game’s interface.