extends CogitoAttribute classname CogitoLightmeter NOTE: This is currently quite…
- User
extends CogitoAttribute class_name CogitoLightmeter
NOTE: This is currently quite expensive on performance due to the get_average_color function.
@export_group("Lightmeter Performance") ##Should light be updating constantly or only when player moves? Disable to constantly update at the cost of performance @export var update_on_move_only : bool = true
Sets a time interval to update the lightmeter. Can be used in addition to move-only to improve performance. Set to 0 to turn off.
@export var update_frequency: float = 1.0 ##Lower for better performance @export var subviewport_resolution : int = 256 ##Interpolation used for get_average_color function. Default for Lightmeter is Lanczos, change for better performance @export var interpolation_method: Image.Interpolation = Image.INTERPOLATE_LANCZOS
@onready var sub_viewport := SubViewport/LightDetection @onready var texture_rect := SubViewport/LightDetection/ColorRect @onready var timer: Timer = $Timer @onready var previous_position : Vector3 = get_parent().global_position
func _ready() -> void: if update_frequency > 0: timer.wait_time = update_frequency timer.timeout.connect(on_timeout) timer.start()
sub_viewport.size = Vector2(subviewport_resolution, subviewport_resolution)func get_average_color(texture: ViewportTexture) -> Color: var image = texture.get_image() # Get the Image of the input texture image.resize(1, 1,interpolation_method) # Resize the image to one pixel return image.get_pixel(0, 0) # Read the color of that pixel
func on_timeout(): update_lightmeter_attribute() timer.start()
func update_lightmeter_attribute(): light_detection.global_position = get_parent().global_position # Make light detection follow the player previous_position = light_detection.global_position var texture = sub_viewport.get_texture() # Get the ViewportTexture from the SubViewport #texture_rect.texture = texture # Display this texture on the TextureRect var color = get_average_color(texture) # Get the average color of the ViewportTexture color_rect.color = color # Display the average color on the ColorRect set_attribute(color.get_luminance() * 100, 100)
func _process(_delta: float) -> void: #Skip updating every frame is update_on_move_only is enabled if update_on_move_only: # A little check to reduce how many times the light detection is done. if previous_position == get_parent().global_position: return
update_lightmeter_attribute() - Assistant
The
CogitoLightmeterclass you've provided appears to be a script designed for use within the Godot Engine, presumably to manage light detection and color averaging in a 3D space. Below, I'll explain the key components of the script and suggest some improvements for clarity and performance.Overview of Components:
-
Export Variables:
update_on_move_only: Determines whether the lightmeter should update only when the player moves.update_frequency: Interval at which updates occur, allowing for more controlled light detection sampling.subviewport_resolution: Sets the resolution of the subviewport to balance fidelity and performance.interpolation_method: Determines how theget_average_colorfunction processes images for performance versus quality.
-
Nodes:
- The script uses nodes like
SubViewport,LightDetection,TextureRect, andColorRectto manage graphics and calculate light.
- The script uses nodes like
-
Timers:
- A
Timernode is used to automate updates based onupdate_frequency.
- A
-
Functions:
_ready(): Initializes various configurations, sets up the timer, and defines the viewport size.get_average_color(): A function that processes a texture to return the average color.on_timeout(): Triggered when the timer times out, prompting an update to the light meter.update_lightmeter_attribute(): Updates the position for light detection, captures the average color, and sets the light attribute._process(): Checks the player's position and decides if an update is necessary based on theupdate_on_move_onlysetting.
Suggested Improvements
-
Code Clarity:
- Adding comments to explain the purpose of methods and blocks of code will help maintainability.
- Using more descriptive variable names could also clarify intentions.
-
Performance Optimization:
- Check for changes in position using a small threshold (instead of strict equality), which can help in cases of floating-point inaccuracies.
- You could potentially limit the invocation of
get_average_colorby adding a radius check for the light detection, instead of updating whenever the position changes.
-
Signal Connections:
- Instead of connecting to
timer.timeoutdirectly in_ready, consider using a separate function to manage signal connections for better modularity.
- Instead of connecting to
-
Error Handling:
- Implement checks or logging for cases where the texture may not be valid, preventing runtime errors.
Here's the improved version of your code:
extends CogitoAttribute class_name CogitoLightmeter @export_group("Lightmeter Performance") @export var update_on_move_only: bool = true @export var update_frequency: float = 1.0 @export var subviewport_resolution: int = 256 @export var interpolation_method: Image.Interpolation = Image.INTERPOLATE_LANCZOS @onready var sub_viewport := $SubViewport @onready var light_detection := $SubViewport/LightDetection @onready var texture_rect := $SubViewport/LightDetection/TextureRect @onready var color_rect := $SubViewport/LightDetection/ColorRect @onready var timer: Timer = $Timer @onready var previous_position: Vector3 = get_parent().global_position func _ready() -> void: if update_frequency > 0: timer.wait_time = update_frequency timer.timeout.connect(on_timeout) timer.start() sub_viewport.size = Vector2(subviewport_resolution, subviewport_resolution) func get_average_color(texture: ViewportTexture) -> Color: var image = texture.get_image() image.resize(1, 1, interpolation_method) return image.get_pixel(0, 0) func on_timeout() -> void: update_lightmeter_attribute() timer.start() func update_lightmeter_attribute() -> void: light_detection.global_position = get_parent().global_position previous_position = light_detection.global_position var texture = sub_viewport.get_texture() if texture: var color = get_average_color(texture) color_rect.color = color set_attribute(color.get_luminance() * 100, 100) func _process(delta: float) -> void: if update_on_move_only: if previous_position.distance_to(get_parent().global_position) < 0.01: return update_lightmeter_attribute()Key Adjustments Made
- Distance Check: Replaced strict equality with a distance check to avoid issues with floating-point precision errors.
- Error Checking: Ensured that the update only occurs if the texture is valid.
- Code Formatting: Improved comments and overall structure for readability.
This approach maintains functionality while offering a clearer and potentially more efficient implementation for the lightmeter logic.
-
- User
extends CogitoAttribute
The rate at which sanity decays when decaying.
@export var decay_rate : float
The rate at which sanity increases when recovering.
@export var recovery_rate : float
Sets if sanity decaus when player visibility attribute is zero.
@export var decay_in_darkness : bool = false
Amount of damage the player gets when player is out of sanity.
@export var damage_when_zero : float = 2
var is_decaying : bool = false var is_recovering : bool = false var recovery_max : float var player : Node3D
func _ready() -> void: value_current = value_start player = get_parent()
func _process(delta): if is_decaying: subtract(decay_rate * delta)
if is_recovering and value_current < recovery_max: add(recovery_rate * delta) if value_current <= 0: print("Taking damage due to 0 sanity.") player.decrease_attribute("health",damage_when_zero * delta)func start_decay(): is_decaying = true
func stop_decay(): is_decaying = false
func start_recovery(passed_recovery_rate, passed_recovery_max): stop_decay() recovery_rate = passed_recovery_rate recovery_max = passed_recovery_max is_recovering = true
func stop_recovery(): is_recovering = false start_decay()
func on_visibility_changed(_visibility_name:String, _visibility_current:float, _visibility_max:float, _has_increased:bool): if _visibility_current > 0: stop_decay() start_recovery(recovery_rate, (_visibility_current / _visibility_max * value_max))
if _visibility_current <= 0 and decay_in_darkness: if is_recovering: stop_recovery() else: start_decay() - Assistant
The
CogitoSanityclass you've shared is built for managing a sanity attribute within a game, likely incorporating mechanics for decay and recovery of sanity based on player visibility. Below, I'll provide an overview of the script, suggest improvements for clarity, efficiency, and robustness, and present the enhanced version of the code.Overview of Components:
-
Export Variables:
decay_rate: The rate at which sanity decreases over time.recovery_rate: The rate at which sanity increases during recovery.decay_in_darkness: A boolean that specifies whether sanity decays when visibility is zero.damage_when_zero: How much damage the player takes when their sanity reaches zero.
-
State Variables:
is_decaying: A flag indicating if sanity is decaying.is_recovering: A flag indicating if sanity is recovering.recovery_max: A float representing the maximum possible recovery for sanity.player: A reference to the player node.
-
Functions:
_ready(): Initializes the current sanity value and gets a reference to the player._process(delta): Updates sanity based on decay or recovery conditions every frame.start_decay(),stop_decay(): Functions to start and stop the decay process.start_recovery(),stop_recovery(): Functions to manage the recovery process.on_visibility_changed(): Responds to visibility changes affecting the sanity state.
Suggested Improvements
-
Code Organization:
- Group the export variables, state variables, and functions logically for better readability.
- Consider adding comments to clarify each method's purpose in more depth.
-
Error Handling:
- Ensure the player node is not null and validate values before performing operations like health reduction.
-
Clarity in Process Logic:
- Use descriptive variable names in functions where necessary to clarify the logic.
- Consider consolidating checks within
_processfor clarity.
-
Guard Clauses:
- Use early returns in functions where applicable to flatten code structure and reduce nesting.
Here's the improved version of your code incorporating the suggestions:
extends CogitoAttribute ## The rate at which sanity decays when decaying. @export var decay_rate: float ## The rate at which sanity increases when recovering. @export var recovery_rate: float ## Sets if sanity decays when player visibility attribute is zero. @export var decay_in_darkness: bool = false ## Amount of damage the player takes when sanity reaches zero. @export var damage_when_zero: float = 2 var is_decaying: bool = false var is_recovering: bool = false var recovery_max: float var player: Node3D func _ready() -> void: value_current = value_start player = get_parent() func _process(delta: float) -> void: if is_decaying: subtract(decay_rate * delta) if is_recovering and value_current < recovery_max: add(recovery_rate * delta) if value_current <= 0: if player: # Ensure player is valid before trying to modify health print("Taking damage due to 0 sanity.") player.decrease_attribute("health", damage_when_zero * delta) func start_decay() -> void: is_decaying = true func stop_decay() -> void: is_decaying = false func start_recovery(passed_recovery_rate: float, passed_recovery_max: float) -> void: stop_decay() recovery_rate = passed_recovery_rate recovery_max = passed_recovery_max is_recovering = true func stop_recovery() -> void: is_recovering = false start_decay() func on_visibility_changed(_visibility_name: String, _visibility_current: float, _visibility_max: float, _has_increased: bool) -> void: if _visibility_current > 0: stop_decay() start_recovery(recovery_rate, (_visibility_current / _visibility_max) * value_max) elif decay_in_darkness: if is_recovering: stop_recovery() else: start_decay()Key Adjustments Made
- Validation Check: Added a check to ensure that the player node is valid before attempting to apply damage.
- Distinct Return Structures: Used
elifinstead of a separateifto improve readability in theon_visibility_changed()function. - Code Clarity: Improved comments and parameter names for better understanding.
- Guard Logic: Used a structured approach to clarify the different states of balance between recovery and decay.
These modifications provide robustness and readability, ensuring that the functionality of sanity management remains clear and maintainable.
-
- User
extends CogitoAttribute
@export var stamina_regen_speed : float = 1 @export var run_exhaustion_speed : float = 1 @export var jump_exhaustion : float = 1 @export var regenerate_after : float = 2 @export var auto_regenerate : bool = true
var regen_timer : Timer var stamina_regen_wait : float var is_regenerating : bool var player : Node3D
func _ready() -> void: value_current = value_start player = get_parent()
regen_timer = Timer.new() regen_timer.wait_time = regenerate_after add_child(regen_timer) regen_timer.timeout.connect(_on_regen_timer_timeout)func _process(delta): if is_regenerating: add(stamina_regen_speed * delta) if value_current >= value_max: is_regenerating = false
# Decreases stamina during sprinting if player.is_sprinting and player.current_speed > player.WALKING_SPEED and player.velocity.length() > 0.1: regen_timer.stop() is_regenerating = false subtract(run_exhaustion_speed * delta) if !is_regenerating and regen_timer.is_stopped() and value_current < value_max and !player.is_sprinting: regen_timer.start()func _on_regen_timer_timeout(): if !is_regenerating: is_regenerating = true
- Assistant
The
CogitoStaminaclass you've provided is responsible for managing a player's stamina in a game, including stamina regeneration and depletion during actions like running and jumping. Below, I'll explain how the system works, identify potential improvements, and then present an enhanced version of the code.Overview of Components:
-
Export Variables:
stamina_regen_speed: The rate at which stamina regenerates over time.run_exhaustion_speed: The rate of stamina depletion during running.jump_exhaustion: The stamina cost for jumping (although this variable is not used in the provided code).regenerate_after: The cooldown time before stamina regeneration starts after the player stops running.auto_regenerate: A flag that determines if stamina regenerates automatically after exhaustion.
-
State Variables:
regen_timer: A timer that controls when to start regenerating stamina.stamina_regen_wait: A variable intended to track the wait time for regeneration (not used).is_regenerating: A flag indicating whether stamina is currently regenerating.player: A reference to the player node.
-
Functions:
_ready(): Initializes the stamina value and sets up the regeneration timer._process(delta): Updates stamina based on the player's actions every frame. This includes consuming stamina while sprinting and starting regeneration when conditions are met._on_regen_timer_timeout(): Called when the regeneration timer times out, enabling stamina regeneration.
Suggested Improvements
-
Use of the
jump_exhaustionVariable:- The
jump_exhaustionvariable is declared but not utilized. You may want to incorporate it in a way that subtracts stamina when the player jumps.
- The
-
Timer Management:
- Ensure that the timer is only created once, and consider separating the timer logic for clarity.
-
Code Clarity:
- Include comments and potentially rename variables and function parameters for better readability.
- The
stamina_regen_waitvariable is unnecessary if you only need to track the start of regeneration, so it should be removed.
-
Performance and Readability:
- Clarify the logic in
_processby adding constants for conditions likeSTAMINA_THRESHOLDto avoid magic numbers. - Use guard clauses to reduce nested conditions and improve flow.
- Clarify the logic in
-
Health and Safety Checks:
- Verify that the stamina value does not exceed maximum limits to prevent unintended behavior.
Here’s the improved version of your code:
extends CogitoAttribute @export var stamina_regen_speed: float = 1 @export var run_exhaustion_speed: float = 1 @export var jump_exhaustion: float = 1 @export var regenerate_after: float = 2 @export var auto_regenerate: bool = true var regen_timer: Timer var is_regenerating: bool var player: Node3D func _ready() -> void: value_current = value_start player = get_parent() regen_timer = Timer.new() regen_timer.wait_time = regenerate_after add_child(regen_timer) regen_timer.timeout.connect(_on_regen_timer_timeout) func _process(delta: float) -> void: if is_regenerating: add(stamina_regen_speed * delta) if value_current >= value_max: value_current = value_max is_regenerating = false # Decrease stamina during sprinting if player.is_sprinting and player.current_speed > player.WALKING_SPEED and player.velocity.length() > 0.1: stop_regen() subtract(run_exhaustion_speed * delta) # Start regeneration if the player is not sprinting and stamina is low if !is_regenerating and regen_timer.is_stopped() and value_current < value_max and !player.is_sprinting: regen_timer.start() func stop_regen() -> void: regen_timer.stop() is_regenerating = false func _on_regen_timer_timeout() -> void: if !is_regenerating: is_regenerating = trueKey Adjustments Made
- Incorporated
jump_exhaustion: You might want to incorporate this in your logic as needed for jumping. This example code still doesn’t apply it, but a simple implementation can subtract its value at the appropriate event in a jumping function. - Guard Clause for Timer Logic: Reduced nested if statements and added a
stop_regen()helper function to manage the timer stopping clearer. - Max Value Check: Ensured that
value_currentdoes not exceedvalue_maxduring regeneration. - Simplified Logic: Cleaned up the logic to make the flow easier to follow.
These changes enhance the stamina management functionality, providing a clearer structure while maintaining the intended gameplay mechanics.
-
- User
extends Node3D
This gives broad control of wieldable sway strength. 1 = no change in raw sway amount.
@export_range(1,8) var sway_predivision: float = 3
This gives more granular control of wieldable sway strength.
@export var sway_multiplier : float = .001
func _process(delta: float) -> void: position.x = lerp(position.x,0.0,delta5) position.y = lerp(position.y,0.0,delta5)
func sway(sway_amount: Vector2) -> void: position.x += (sway_amount.x/sway_predivision) * sway_multiplier position.y += (sway_amount.y/sway_predivision) * sway_multiplier
- Assistant
The
Node3Dscript you've provided is responsible for handling a sway effect on a 3D object, likely something that a player can wield, such as a weapon or tool. The script allows for adjustments in the sway behavior based on user-defined parameters and a sway method.Overview of Components:
-
Export Variables:
sway_predivision: This variable controls the intensity of the sway. A higher value reduces the sway.sway_multiplier: This variable controls how much sway is applied to the position based on the input sway amount.
-
Functions:
_process(delta): This method is called every frame and ensures that the position of the object smoothly returns to zero (which might represent a neutral position).sway(sway_amount: Vector2): This method applies the sway to the object's position based on the input vector, scaled bysway_predivisionandsway_multiplier.
Suggested Improvements:
-
Variable Names: Ensure clarity in variable names to indicate what they represent, although they are quite understandable in this context.
-
Adjustable Sway Speed: Instead of hardcoding the lerp speed (
delta * 5), consider making it an export variable to adjust the recovery speed of the sway effect dynamically. -
Adding Constraints: Depending on the application, it might be beneficial to constrain the position to ensure it doesn’t go too far from a neutral position.
-
Sway Limitation: Cut-off limits could be placed on the
positionto avoid unintentional position drift. -
Documentation: Adding more comments to clarify how each piece functions would help others who might read or modify this script.
Here’s the improved version of your code:
extends Node3D ## This gives broad control of wieldable sway strength. 1 = no change in raw sway amount. @export_range(1, 8) var sway_predivision: float = 3 ## This gives more granular control of wieldable sway strength. @export var sway_multiplier: float = .001 ## Speed at which the object returns to its neutral position @export var sway_recovery_speed: float = 5.0 func _process(delta: float) -> void: # Smoothly return the object's position to the center position.x = lerp(position.x, 0.0, delta * sway_recovery_speed) position.y = lerp(position.y, 0.0, delta * sway_recovery_speed) func sway(sway_amount: Vector2) -> void: # Apply sway to the object's position based on the input sway amount position.x += (sway_amount.x / sway_predivision) * sway_multiplier position.y += (sway_amount.y / sway_predivision) * sway_multiplierKey Adjustments Made:
-
Sway Recovery Speed as a Variable: Introduced
sway_recovery_speedas an export variable making the recovery speed adjustable in the editor. -
Clear Comments: Added comments to clarify the purpose of the
_processandswayfunctions, improving the readability of the code.
This refactoring maintains the original functionality while providing better flexibility and clarity, making it easier to tweak parameters in the Godot editor for different gameplay scenarios.
-
- User
extends AudioStreamPlayer3D
class_name FootstepSurfaceDetector
@export var generic_fallback_footstep_profile : AudioStreamRandomizer @export var footstep_material_library : FootstepMaterialLibrary @export var generic_fallback_landing_profile : AudioStreamRandomizer @export var landing_material_library : FootstepMaterialLibrary var last_result var parent_rid : RID
func _ready(): parent_rid = get_parent().get_rid() if not generic_fallback_footstep_profile: printerr("FootstepSurfaceDetector - No generic fallback footstep profile is assigned") if not generic_fallback_landing_profile: printerr("FootstepSurfaceDetector - No generic fallback landing profile is assigned")
func play_footstep(): _play_interaction("footstep")
func play_landing(): _play_interaction("landing")
func _play_interaction(interaction_type: String): var query = PhysicsRayQueryParameters3D.create(global_position, global_position + Vector3(0, -1, 0)) query.exclude = [parent_rid] var result = get_world_3d().direct_space_state.intersect_ray(query) if result: last_result = result if interaction_type == "footstep": if _play_by_footstep_surface(result.collider, interaction_type): return elif _play_by_material(result.collider, footstep_material_library, generic_fallback_footstep_profile, interaction_type): return elif interaction_type == "landing": if _play_by_landing_surface(result.collider, interaction_type): return elif _play_by_material(result.collider, landing_material_library, generic_fallback_landing_profile, interaction_type): return
func _play_by_footstep_surface(collider : Node3D, interaction_type: String) -> bool: #check for footstep surface as a child of the collider var footstep_surface_child : AudioStreamRandomizer = _get_footstep_surface_child(collider) #if a child footstep surface was found, then play the sound defined by it if footstep_surface_child: _play_footstep(footstep_surface_child, interaction_type) return true #handle footstep surface settings elif collider is FootstepSurface and collider.footstep_profile: _play_footstep(collider.footstep_profile, interaction_type) return true return false
func _play_by_landing_surface(collider: Node3D, interaction_type: String) -> bool: return _play_by_footstep_surface(collider, interaction_type)
func _play_by_material(collider: Node3D, material_library: FootstepMaterialLibrary, fallback_profile: AudioStreamRandomizer, interaction_type: String) -> bool: if material_library: #find surface material var material: Material = _get_surface_material(collider) #if a material was found if material: #get a profile from our library var profile: AudioStreamRandomizer = material_library.get_footstep_profile_by_material(material) #found profile, use it if profile: _play_footstep(profile, interaction_type) return true # If no specific material profile is found, play the fallback profile _play_footstep(fallback_profile, interaction_type) return false
func _get_footstep_surface_child(collider : Node3D) -> AudioStreamRandomizer: #find all children of the collider static body that are of type "FootstepSurface" var footstep_surfaces = collider.find_children("", "FootstepSurface") if footstep_surfaces: #use the first footstep_surface child found return footstep_surfaces[0].footstep_profile return null
func _get_surface_material(collider : Node3D) -> Material: var mesh_instance = null var meshes = [] if collider is CSGShape3D: if collider is CSGCombiner3D: #composite mesh if collider.material_override: return collider.material_override meshes = collider.get_meshes() else: return collider.material elif collider is StaticBody3D or collider is RigidBody3D: #find all children of the collider static body that are of type "MeshInstance3D" #if there are multiple materials, just default to the first one found if collider.get_parent() is MeshInstance3D: mesh_instance = collider.get_parent() else: var mesh_instances = collider.find_children("", "MeshInstance3D") if mesh_instances: if len(mesh_instances) == 1: mesh_instance = mesh_instances[0] else: meshes = mesh_instances
if meshes: #TODO: Handle multiple meshes mesh_instance = meshes[0] if mesh_instance and 'mesh' in mesh_instance: var mesh = mesh_instance.mesh if mesh.get_surface_count() == 0: return null elif mesh.get_surface_count() == 1: return mesh.surface_get_material(0) else: var face = null var ray = last_result['position'] - global_position var faces = mesh.get_faces() var aabb = mesh.get_aabb() as AABB var accuracy = round(4*aabb.size.length_squared()) # dynamically calculate a reasonable grid size var snap = aabb.size/accuracy # this will be the size of our units to snap to var coord = null for i in range(len(faces) / 3): # first, figure out what face we're standing on var face_idx = i * 3 var a = mesh_instance.to_global(faces[face_idx]) var b = mesh_instance.to_global(faces[face_idx+1]) var c = mesh_instance.to_global(faces[face_idx+2]) var ray_t = Geometry3D.ray_intersects_triangle(global_position,ray,a,b,c) if ray_t: face = faces.slice(face_idx,face_idx+3) # round out vert coordinates to avoid floating point errors coord = [round(faces[face_idx]/snap),round(faces[face_idx+1]/snap),round(faces[face_idx+2]/snap)] break var mat = null if face: for surface in range(mesh.get_surface_count()): var surf = mesh.surface_get_arrays(surface)[0] var has_vert_a = false var has_vert_b = false var has_vert_c = false for vert in surf: var vert_coord = round(vert/snap) has_vert_a = has_vert_a or vert_coord == coord[0] has_vert_b = has_vert_b or vert_coord == coord[1] has_vert_c = has_vert_c or vert_coord == coord[2] if has_vert_a and has_vert_b and has_vert_c: # we found it! note the material and break free! mat = mesh.surface_get_material(surface) break if has_vert_a and has_vert_b and has_vert_c: break return mat return nullfunc _play_footstep(profile : AudioStreamRandomizer, interaction_type: String):
if interaction_type == "footstep": stream = profile play() elif interaction_type == "landing": #Setup QuickAudio landing player so that it can use its own pitch/volume parameters var playerNode = get_parent() var LandingVolume = playerNode.LandingVolume var LandingPitch = playerNode.LandingPitch var LandingPlayer = Audio.play_sound_3d(profile, false) LandingPlayer.pitch_scale = LandingPitch LandingPlayer.volume_db = LandingVolume LandingPlayer.global_position = global_position LandingPlayer.play() - Assistant
The
FootstepSurfaceDetectorclass you've shared is designed to play footstep and landing audio effects based on the material that the player is interacting with in a 3D environment. This class uses raycasting to determine the surface type and appropriately selects audio profiles from assigned libraries. Below, I'll break down the functionality, suggest improvements, and present an enhanced version of your code.Overview of Components:
-
Export Variables:
generic_fallback_footstep_profile: The default audio profile for footstep sounds.footstep_material_library: A library to retrieve audio profiles based on material.generic_fallback_landing_profile: Default audio profile for landing sounds.landing_material_library: A library to retrieve landing audio profiles based on material.
-
State Variables:
last_result: Stores the result of the last raycast hit.parent_rid: Used to exclude the current node from the raycast.
-
Functions:
_ready(): Initializes the object and checks for required profiles.play_footstep(): Triggers the footstep audio playback.play_landing(): Triggers the landing audio playback._play_interaction(): Handles audio playback interactions based on the raycast result.- Various helper methods to determine footstep surfaces, handle materials, and invoke audio playback.
Suggested Improvements:
-
Code Clarity and Documentation: Enhance readability by adding comments to clarify the logic and purpose of each function.
-
Unused Variables: The variable
last_resultis potentially reused in different contexts (like surface material retrieval), it may be useful to rename it or document where it gets used. -
Error Handling: Add checks to handle scenarios where audio profiles or materials might not be valid after retrieval to avoid runtime errors.
-
Efficiency: Consider avoiding multiple calls to
get_children()where possible, and optimize raycasting to limit calculations. -
Materials Handling: Ensure that the
Materialclass used is consistent and provides necessary properties for footstep sound determined by surface type.
Here’s the improved and enhanced version of your class:
extends AudioStreamPlayer3D class_name FootstepSurfaceDetector @export var generic_fallback_footstep_profile: AudioStreamRandomizer @export var footstep_material_library: FootstepMaterialLibrary @export var generic_fallback_landing_profile: AudioStreamRandomizer @export var landing_material_library: FootstepMaterialLibrary var last_result: Dictionary # Storing the last raycast hit result. var parent_rid: RID func _ready() -> void: parent_rid = get_parent().get_rid() if not generic_fallback_footstep_profile: printerr("FootstepSurfaceDetector - No generic fallback footstep profile is assigned") if not generic_fallback_landing_profile: printerr("FootstepSurfaceDetector - No generic fallback landing profile is assigned") func play_footstep() -> void: _play_interaction("footstep") func play_landing() -> void: _play_interaction("landing") func _play_interaction(interaction_type: String) -> void: var query = PhysicsRayQueryParameters3D.create(global_position, global_position + Vector3(0, -1, 0)) query.exclude = [parent_rid] var result = get_world_3d().direct_space_state.intersect_ray(query) if result: last_result = result if interaction_type == "footstep": if _play_by_footstep_surface(result.collider, interaction_type): return elif _play_by_material(result.collider, footstep_material_library, generic_fallback_footstep_profile, interaction_type): return elif interaction_type == "landing": if _play_by_landing_surface(result.collider, interaction_type): return elif _play_by_material(result.collider, landing_material_library, generic_fallback_landing_profile, interaction_type): return func _play_by_footstep_surface(collider: Node3D, interaction_type: String) -> bool: # Attempt to find a footstep surface profile from the collider var footstep_surface_child: AudioStreamRandomizer = _get_footstep_surface_child(collider) if footstep_surface_child: _play_footstep(footstep_surface_child, interaction_type) return true elif collider is FootstepSurface and collider.footstep_profile: _play_footstep(collider.footstep_profile, interaction_type) return true return false func _play_by_landing_surface(collider: Node3D, interaction_type: String) -> bool: # Similar to footstep, but can be adjusted for different handling if necessary return _play_by_footstep_surface(collider, interaction_type) func _play_by_material(collider: Node3D, material_library: FootstepMaterialLibrary, fallback_profile: AudioStreamRandomizer, interaction_type: String) -> bool: if material_library: var material: Material = _get_surface_material(collider) if material: var profile: AudioStreamRandomizer = material_library.get_footstep_profile_by_material(material) if profile: _play_footstep(profile, interaction_type) return true _play_footstep(fallback_profile, interaction_type) # Fallback to the default profile return false func _get_footstep_surface_child(collider: Node3D) -> AudioStreamRandomizer: var footstep_surfaces = collider.find_children("", "FootstepSurface") if footstep_surfaces.size() > 0: return footstep_surfaces[0].footstep_profile return null func _get_surface_material(collider: Node3D) -> Material: var mesh_instance: MeshInstance3D var meshes = [] if collider is CSGShape3D: if collider is CSGCombiner3D and collider.material_override: return collider.material_override meshes = collider.get_meshes() elif collider is StaticBody3D or collider is RigidBody3D: mesh_instance = collider.get_parent() as MeshInstance3D if collider.get_parent() is MeshInstance3D else null if not mesh_instance: meshes = collider.find_children("", "MeshInstance3D") if meshes: if not mesh_instance: mesh_instance = meshes[0] # Default to the first mesh instance if mesh_instance and 'mesh' in mesh_instance: var mesh = mesh_instance.mesh if mesh.get_surface_count() == 0: return null elif mesh.get_surface_count() == 1: return mesh.surface_get_material(0) return _find_material_from_faces(mesh_instance, mesh, last_result['position']) return null func _find_material_from_faces(mesh_instance: MeshInstance3D, mesh: Mesh, position: Vector3) -> Material: var faces = mesh.get_faces() var aabb = mesh.get_aabb() as AABB var accuracy = round(4 * aabb.size.length_squared()) # Dynamically calculate a reasonable grid size var snap = aabb.size / accuracy # Size of units to snap to var coord = null var face = null var ray = position - global_position for i in range(len(faces) / 3): var face_idx = i * 3 var a = mesh_instance.to_global(faces[face_idx]) var b = mesh_instance.to_global(faces[face_idx + 1]) var c = mesh_instance.to_global(faces[face_idx + 2]) if Geometry3D.ray_intersects_triangle(global_position, ray, a, b, c): face = faces.slice(face_idx, face_idx + 3) coord = [round(faces[face_idx] / snap), round(faces[face_idx + 1] / snap), round(faces[face_idx + 2] / snap)] break if face: for surface in range(mesh.get_surface_count()): var surf = mesh.surface_get_arrays(surface)[0] var has_vert = [false, false, false] for vert in surf: var vert_coord = round(vert / snap) has_vert[0] = has_vert[0] or vert_coord == coord[0] has_vert[1] = has_vert[1] or vert_coord == coord[1] has_vert[2] = has_vert[2] or vert_coord == coord[2] if has_vert.all(): return mesh.surface_get_material(surface) return null func _play_footstep(profile: AudioStreamRandomizer, interaction_type: String) -> void: if interaction_type == "footstep": stream = profile play() elif interaction_type == "landing": var playerNode = get_parent() var landingPlayer = Audio.play_sound_3d(profile, false) landingPlayer.pitch_scale = playerNode.LandingPitch landingPlayer.volume_db = playerNode.LandingVolume landingPlayer.global_position = global_position landingPlayer.play()Key Adjustments Made:
-
Function Separation: Separated the logic handling finding the appropriate material into a dedicated function (
_find_material_from_faces) for better readability. -
Material Handling Improvements: Improved handling of how materials are obtained from meshes, adding more structured checks.
-
Error Handling: Added checks for valid variables and descriptive error messages for clarity.
-
Clear Documentation: Enhanced comments throughout the code to clarify what each function and segment is doing, which is particularly useful for future maintenance.
-
Array Handling Safeguards: Ensured better control when accessing child arrays and lengths.
These enhancements contribute significantly to the clarity, robustness, and maintainability of your footstep and landing audio solution.
-
- User
@icon("res://addons/cogito/Assets/Graphics/Editor/Icon_AutoPickUpZone.svg") class_name AutoPickUpZone extends Area3D
signal auto_picked_up_item()
This is useful when you have pick up items that are frustrating, tedious, or required
and provides a smoother experience than only using the default raycasting + input interaction.
Items listed here will be picked up automatically when they enter the area
@export var auto_pick_up_items: Array[InventoryItemPD] = [] @export var _player_interaction_component: PlayerInteractionComponent var player: CogitoPlayer @onready var standing_collider: CollisionShape3D = CrouchingZone
func _ready() -> void: player = get_parent()
func _on_body_entered(body: Node3D) -> void: _attempt_pick_up(body)
func _physics_process(_delta) -> void: _update_shape()
func _update_shape() -> void: # Uses a shorter collision cylinder when crouching if player.is_crouching: if !standing_collider.disabled: standing_collider.disabled = true if crouching_collider.disabled: crouching_collider.disabled = false else: if standing_collider.disabled: standing_collider.disabled = false if !crouching_collider.disabled: crouching_collider.disabled = true
func _attempt_pick_up(body: Node3D) -> void: var child_count: int = body.get_child_count() # search recursively as PickupComponents tend to be childed near the back for i in range(child_count-1, -1, -1): if body.get_child(i) is not PickupComponent: continue
var pick_up_component = body.get_child(i) as PickupComponent # This prevents cogito projectiles if body is CogitoProjectile and !(body as CogitoProjectile).can_pick_up: #print("can't pick up projectile as it has just been fired") continue if auto_pick_up_items.has(pick_up_component.slot_data.inventory_item): pick_up_component.interact(_player_interaction_component) auto_picked_up_item.emit() # Exit loop after detecting a pick up component (should only be one) breakTODO: may require save functionality to properly implement altering the item list
#func new_item_list(new_items: Array[InventoryItemPD]) -> void: #auto_pick_up_items = new_items.duplicate() #CogitoGlobals.debug_log(true,"AutoPickUpZone.gd", "Created a new auto pick up list")
#func add_item_to_list(item: InventoryItemPD) -> void: #if !auto_pick_up_items.has(item): #auto_pick_up_items.append(item) #CogitoGlobals.debug_log(true,"AutoPickUpZone.gd", "Added %s to auto pick up list" % item.name)
#func remove_item_from_list(item: InventoryItemPD) -> void: #if auto_pick_up_items.has(item): #auto_pick_up_items.erase(item) #CogitoGlobals.debug_log(true,"AutoPickUpZone.gd", "Removed %s from auto pick up list" % item.name)
- Assistant
The
AutoPickUpZoneclass is a part of the Godot Engine that automates the picking up of items when a player character enters a specified area. This avoids the friction often caused by manual item collection mechanics, especially in fast-paced gameplay. Below, I'll explain the components, provide suggestions for improvements, and present a refined version of your code.Overview of Components:
-
Export Variables:
auto_pick_up_items: An array of items that are automatically picked up when they enter the area._player_interaction_component: A reference to the player's interaction component, allowing interaction with pickup items.
-
State Variables:
player: A reference to the player node.standing_colliderandcrouching_collider: Shape nodes that define the area for item pickups when standing or crouching.
-
Functions:
_ready(): Initializes the player reference._on_body_entered(body: Node3D): Triggered when an object enters the area, trying to pick it up._physics_process(_delta): Updates collider shape based on the player’s stature (standing or crouching)._attempt_pick_up(body: Node3D): Searches for pick-up items within the entered body and interacts with them.
Suggested Improvements:
-
Consistency in Naming: Ensure that naming conventions are consistent, especially regarding private and public prefixes, if applicable.
-
Player Interaction Component: Ensure that
_player_interaction_componentis initialized correctly. It may be beneficial to validate if it is assigned properly. -
Type Checking: When accessing child nodes, consider checking both type and whether the child exists.
-
Improved Logging: Uncomment and improve the logging functionality to provide feedback when items are added or removed. This aids in debugging.
-
Utilize Signals: If you want to communicate item pickups to other parts of the game, consider using the signal properly instead of a simple comment placeholder.
-
Clarity in Comments: Some comments may be updated for clarity or removed if the code is self-explanatory.
Here’s an improved version of your
AutoPickUpZoneclass:@icon("res://addons/cogito/Assets/Graphics/Editor/Icon_AutoPickUpZone.svg") class_name AutoPickUpZone extends Area3D signal auto_picked_up_item() ## Items listed here will be picked up automatically when they enter the area @export var auto_pick_up_items: Array[InventoryItemPD] = [] @export var _player_interaction_component: PlayerInteractionComponent var player: CogitoPlayer @onready var standing_collider: CollisionShape3D = $StandingZone @onready var crouching_collider: CollisionShape3D = $CrouchingZone func _ready() -> void: player = get_parent() if not _player_interaction_component: printerr("AutoPickUpZone: No Player Interaction Component assigned.") func _on_body_entered(body: Node3D) -> void: _attempt_pick_up(body) func _physics_process(_delta: float) -> void: _update_shape() func _update_shape() -> void: # Uses a shorter collision cylinder when crouching if player.is_crouching: standing_collider.disabled = true crouching_collider.disabled = false else: standing_collider.disabled = false crouching_collider.disabled = true func _attempt_pick_up(body: Node3D) -> void: if body.get_child_count() == 0: return # Search for PickupComponent in the children for i in range(body.get_child_count() - 1, -1, -1): var child = body.get_child(i) if child is PickupComponent: if body is CogitoProjectile and not (body as CogitoProjectile).can_pick_up: continue # Skip projectiles that cannot be picked up var inventory_item = child.slot_data.inventory_item if auto_pick_up_items.has(inventory_item): child.interact(_player_interaction_component) # Trigger the interaction auto_picked_up_item.emit() # Emit the signal break # Exit loop after a successful pickup # Uncomment these methods to allow dynamic item list modification # func new_item_list(new_items: Array[InventoryItemPD]) -> void: # auto_pick_up_items = new_items.duplicate() # CogitoGlobals.debug_log(true, "AutoPickUpZone.gd", "Created a new auto pick up list") # # func add_item_to_list(item: InventoryItemPD) -> void: # if not auto_pick_up_items.has(item): # auto_pick_up_items.append(item) # CogitoGlobals.debug_log(true, "AutoPickUpZone.gd", "Added %s to auto pick up list" % item.name) # # func remove_item_from_list(item: InventoryItemPD) -> void: # if auto_pick_up_items.has(item): # auto_pick_up_items.erase(item) # CogitoGlobals.debug_log(true, "AutoPickUpZone.gd", "Removed %s from auto pick up list" % item.name)Key Adjustments Made:
-
Added Validation Check: The
_ready()function now checks if_player_interaction_componentis properly assigned. -
Simplified
_attempt_pick_upLogic: Cleaned up the process of checking for child pickup components and add comments for more clarity. -
Refined Use of Signals: Kept the signal emission intact, allowing clear communication across the game.
-
Logging: Prepared the commented-out logging mechanism for potential use later.
These changes aim to improve the clarity and robustness of your
AutoPickUpZoneclass while maintaining its core functionality for enhanced gameplay experiences. -
- User
class_name CogitoAttributeUi extends Control
@onready var attribute_icon: TextureRect = HBoxContainer/AttributeBar @onready var attribute_label: Label = $HBoxContainer/AttributeLabel
@export var bar_stylebox: StyleBoxFlat
var assigned_player_attribute : CogitoAttribute
func initiate_attribute_ui(_player_attribute: CogitoAttribute): assigned_player_attribute = _player_attribute
#Setting up icon, bar and label attribute_icon.texture = assigned_player_attribute.attribute_icon attribute_label.text = str(int(assigned_player_attribute.value_current)) bar_stylebox.bg_color = assigned_player_attribute.attribute_color attribute_bar.add_theme_stylebox_override("fill",bar_stylebox) #Setting bar to correct values #attribute_bar.max_value = assigned_player_attribute.value_max #attribute_bar.value = assigned_player_attribute.value_current attribute_bar.init_values(assigned_player_attribute.value_current, assigned_player_attribute.value_max) _player_attribute.attribute_changed.connect(on_attribute_changed)func on_attribute_changed(_attribute_name:String,_value_current:float,_value_max:float,_has_increased:bool): attribute_bar.update_value(_value_current, _value_max) #attribute_bar.max_value = _value_max #attribute_bar.value = _value_current attribute_label.text = str(int(_value_current))
- Assistant
The
CogitoAttributeUiclass you've provided serves as a UI component in Godot that visually represents a player's attribute (such as health, stamina, etc.). It includes an icon, a dynamic bar for visualizing value changes, and a label for displaying the current value. Below, I'll offer an overview of its functionality, suggest improvements, and provide a refactored version of the code.Overview of Components:
-
Nodes:
attribute_icon: ATextureRectnode representing the icon for the attribute.attribute_bar: ACogitoDynamicBarinstance for displaying the current value visually.attribute_label: ALabeldisplaying the current value numerically.
-
Export Variables:
bar_stylebox: AStyleBoxFlatthat defines how the attribute bar looks.
-
State Variable:
assigned_player_attribute: A reference to theCogitoAttributethat this UI element is tied to.
-
Functions:
initiate_attribute_ui(_player_attribute): Initializes the UI elements based on the provided attribute.on_attribute_changed(): Updates the UI when the attribute changes.
Suggested Improvements:
-
Error Handling: Include checks to ensure that
assigned_player_attributehas valid values (e.g., not null). -
Dynamic Updates: Ensure the color and other properties of the bar appropriately update based on attribute changes.
-
Code Clarity and Comments: Enhance comments for clarity on what each part does.
-
Consistent Naming: Maintain a consistent naming convention, especially for parameters and variables.
-
Optimization: Consider removing commented-out code if it is no longer needed for clarity.
Here’s the improved version of your
CogitoAttributeUiclass:class_name CogitoAttributeUi extends Control @onready var attribute_icon: TextureRect = $HBoxContainer/AttributeIcon @onready var attribute_bar: CogitoDynamicBar = $HBoxContainer/AttributeBar @onready var attribute_label: Label = $HBoxContainer/AttributeLabel @export var bar_stylebox: StyleBoxFlat var assigned_player_attribute: CogitoAttribute func initiate_attribute_ui(_player_attribute: CogitoAttribute) -> void: assigned_player_attribute = _player_attribute # Check if the assigned player attribute is valid if not assigned_player_attribute: printerr("CogitoAttributeUi: Assigned player attribute is null.") return # Setting up icon, bar, and label attribute_icon.texture = assigned_player_attribute.attribute_icon attribute_label.text = str(int(assigned_player_attribute.value_current)) # Current value as integer bar_stylebox.bg_color = assigned_player_attribute.attribute_color attribute_bar.add_theme_stylebox_override("fill", bar_stylebox) # Initialize the bar with the correct values attribute_bar.init_values(assigned_player_attribute.value_current, assigned_player_attribute.value_max) # Connect the attribute changed signal assigned_player_attribute.attribute_changed.connect(on_attribute_changed) func on_attribute_changed(_attribute_name: String, _value_current: float, _value_max: float, _has_increased: bool) -> void: # Update the dynamic bar and label when the attribute changes attribute_bar.update_value(_value_current, _value_max) attribute_label.text = str(int(_value_current)) # Update the label with current valueKey Adjustments Made:
-
Null Check for Attribute: Added a check to ensure the
_player_attributeparameter is valid before proceeding to set up the UI elements. -
Removed Commented Code: Eliminated unnecessary commented-out code for a cleaner look.
-
Enhanced Comments: Provided clearer explanations in comments for what each part of the code does.
-
Consistent Format: Ensured consistent formatting and naming conventions in the script for better readability.
These improvements refine the clarity, safety, and maintainability of the
CogitoAttributeUiclass, ensuring that it functions effectively as part of the game's UI for player attributes. -
- User
class_name CogitoDynamicBar extends ProgressBar
@onready var timer: Timer = DifferenceBar
@export var catch_up_time : float = 0.4 @export var difference_color : Color = Color.WHITE
@onready var difference_var_stylebox : StyleBoxFlat = StyleBoxFlat.new() @onready var empty_stylebox : StyleBoxEmpty = StyleBoxEmpty.new()
var value_current: float
func _ready() -> void: timer.wait_time = catch_up_time add_theme_stylebox_override("background",empty_stylebox)
func update_value(_new_value: float,_new_max_value: float): var prev_value = value_current
if max_value != _new_max_value: max_value = _new_max_value difference_bar.max_value = max_value value_current = _new_value value = value_current if value_current < prev_value: timer.start() else: difference_bar.value = value_currentfunc init_values(_value_current: float, _value_max: float): value_current = _value_current max_value = _value_max value = value_current
difference_bar.max_value = max_value difference_bar.value = value difference_var_stylebox.bg_color = difference_color difference_bar.add_theme_stylebox_override("fill",difference_var_stylebox)func _on_timer_timeout() -> void: var catch_up_tween = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC).set_parallel() catch_up_tween.tween_property(difference_bar,"value", value_current,0.2)
- Assistant
The
CogitoDynamicBarclass extendsProgressBarin Godot and is designed to visually represent a value that changes over time (like health, stamina, etc.). This class appears to feature smooth transitions for when values change and can differentiate between new and old values through a secondary progress bar (for displaying differences). Below, I will provide an overview of its functionality, suggest improvements, and give you an enhanced version of the code.Overview of Components:
-
Nodes:
timer: ATimernode used to manage updates to the progress bar.difference_bar: A secondaryProgressBarused to show the difference between the current value and a new value.
-
Export Variables:
catch_up_time: The duration it takes for the difference bar to catch up to the current value.difference_color: The color used to display the difference in the secondary bar.
-
State Variables:
value_current: Stores the current value of the primary bar.
-
Functions:
_ready(): Initializes the timer and sets the background style for the main bar.update_value(_new_value, _new_max_value): Updates the progress bar's value and initiates the catch-up behavior if the new value is less than the previous value.init_values(_value_current, _value_max): Initializes the values of the progress bar and the difference bar._on_timer_timeout(): Responsible for animating the difference bar as it catches up to the current value.
Suggested Improvements:
-
Error Handling: Add checks to ensure that values are within expected ranges to prevent unexpected behavior (e.g., negative values).
-
Dynamic Tween Duration: Allow the
catch_up_timeto be a parameter inupdate_valuefor flexibility instead of hardcoding the tween duration in_on_timer_timeout. -
Type Consistency and Comments: Use float types consistently and enhance comments to explain the purpose of each method and variable more clearly.
-
Avoiding Redundant Assignments: Ensure assignments in
update_value()do not overwrite values unnecessarily.
Here's an improved version of your
CogitoDynamicBarclass:class_name CogitoDynamicBar extends ProgressBar @onready var timer: Timer = $Timer @onready var difference_bar: ProgressBar = $DifferenceBar @export var catch_up_time: float = 0.4 @export var difference_color: Color = Color.WHITE @onready var difference_var_stylebox: StyleBoxFlat = StyleBoxFlat.new() @onready var empty_stylebox: StyleBoxEmpty = StyleBoxEmpty.new() var value_current: float func _ready() -> void: timer.wait_time = catch_up_time add_theme_stylebox_override("background", empty_stylebox) func update_value(_new_value: float, _new_max_value: float) -> void: if _new_max_value < 0: # Ensure max value is non-negative print("Invalid max value, cannot be negative.") return var prev_value = value_current if max_value != _new_max_value: max_value = _new_max_value difference_bar.max_value = max_value value_current = clamp(_new_value, 0, max_value) # Ensure value is within bounds value = value_current if value_current < prev_value: timer.start() else: difference_bar.value = value_current func init_values(_value_current: float, _value_max: float) -> void: value_current = clamp(_value_current, 0, _value_max) # Ensure initial value is valid max_value = _value_max value = value_current difference_bar.max_value = max_value difference_bar.value = value difference_var_stylebox.bg_color = difference_color difference_bar.add_theme_stylebox_override("fill", difference_var_stylebox) func _on_timer_timeout() -> void: # Use the pre-defined catch_up_time for tweening var catch_up_tween = create_tween() catch_up_tween.set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC).set_parallel() catch_up_tween.tween_property(difference_bar, "value", value_current, catch_up_time)Key Improvements Made:
-
Clamping Values: Added clamping for both the current and maximum values to ensure they stay within valid ranges (e.g., non-negative).
-
Dynamic Tween Duration: Kept the tween duration for catching up consistent with the
catch_up_timevariable. -
Improved Comments: Enhanced comments for better clarity throughout the class.
-
Error Checking: Introduced error handling for invalid values, especially for the
max_value.
These enhancements improve the
CogitoDynamicBarclass's robustness, readability, and maintainability, ensuring it serves as an effective component for dynamic progress representation in your game. -
- User
extends Button class_name CogitoUiButton
signal pressed_string(text:String)
var tween_time : float = 0.2 var tween_stylebox : StyleBoxFlat var styleboxes : Dictionary = {} var current_state = BaseButton.DRAW_NORMAL
Will accept ui_accept keys as long as other shortcuts have been used in context
@export var accepts_contextual_enter : bool = false static var used_shortcut = false
var tween : Tween
func _ready() -> void: #Attempt to make this work with focus self.focus_entered.connect(_on_focus_entered) self.focus_exited.connect(_on_focus_exited) self.pressed.connect(_on_pressed)
# Duplicate the normal stylebox. We are going to use it as our base stylebox tween_stylebox = get_theme_stylebox('normal').duplicate() # Save the different styleboxes to be able to tween between their properties later styleboxes[BaseButton.DRAW_NORMAL] = get_theme_stylebox('normal').duplicate() styleboxes[BaseButton.DRAW_HOVER] = get_theme_stylebox('hover').duplicate() styleboxes[BaseButton.DRAW_PRESSED] = get_theme_stylebox('pressed').duplicate() styleboxes[BaseButton.DRAW_HOVER_PRESSED] = get_theme_stylebox('pressed').duplicate() styleboxes[BaseButton.DRAW_DISABLED] = get_theme_stylebox('disabled').duplicate() # Override all the other styleboxes with our tween stylebox add_theme_stylebox_override('normal', tween_stylebox) add_theme_stylebox_override('hover', tween_stylebox) add_theme_stylebox_override('focus', tween_stylebox) add_theme_stylebox_override('pressed', tween_stylebox) add_theme_stylebox_override('disabled', tween_stylebox)func press_button_manually(): pressed.emit()
if tween and tween.is_running(): # Kill the running tween tween.kill() tween = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC).set_parallel() # That tweens some properties of our tween stylebox to the target stylebox depending on the current state var target = styleboxes[BaseButton.DRAW_PRESSED] as StyleBoxFlat tween.tween_property(tween_stylebox, "bg_color", target.bg_color, tween_time) tween.tween_property(tween_stylebox, "border_color", target.border_color, tween_time) tween.tween_property(tween_stylebox, "border_width_left", target.border_width_left, tween_time) tween.connect('finished',unpress)func unpress(): if not tween or tween.is_running() or not tween.is_valid: # we've likely been overridden since, so don't mess with anything return current_state = BaseButton.DRAW_PRESSED # this will be changed on the next frame
func _process(_delta: float) -> void: if get_draw_mode() != current_state: # If the draw mode changed current_state = get_draw_mode()
if tween and tween.is_running(): # Kill the running tween tween.kill() tween = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC).set_parallel() # That tweens some properties of our tween stylebox to the target stylebox depending on the current state var target = styleboxes[current_state] as StyleBoxFlat tween.tween_property(tween_stylebox, "bg_color", target.bg_color, tween_time) tween.tween_property(tween_stylebox, "border_color", target.border_color, tween_time) tween.tween_property(tween_stylebox, "border_width_left", target.border_width_left, tween_time)func _on_focus_entered() -> void: used_shortcut = false # focus changing implies not using shortcuts
if tween and tween.is_running(): # Kill the running tween tween.kill() tween = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC).set_parallel() # That tweens some properties of our tween stylebox to the target stylebox depending on the current state var target = styleboxes[BaseButton.DRAW_HOVER] as StyleBoxFlat tween.tween_property(tween_stylebox, "bg_color", target.bg_color, tween_time) tween.tween_property(tween_stylebox, "border_color", target.border_color, tween_time) tween.tween_property(tween_stylebox, "border_width_left", target.border_width_left, tween_time)func in_context() -> bool: var context = get_viewport().gui_get_focus_owner() if context: var context_owner = context.shortcut_context or context.get_parent_control() var our_context = shortcut_context or get_parent_control() return context_owner == our_context return false
func _on_focus_exited() -> void: if get_viewport().gui_get_focus_owner() == null: # lost focus to a GUI completely used_shortcut = false
if tween and tween.is_running(): # Kill the running tween tween.kill() tween = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC).set_parallel() # That tweens some properties of our tween stylebox to the target stylebox depending on the current state var target = styleboxes[BaseButton.DRAW_NORMAL] as StyleBoxFlat tween.tween_property(tween_stylebox, "bg_color", target.bg_color, tween_time) tween.tween_property(tween_stylebox, "border_color", target.border_color, tween_time) tween.tween_property(tween_stylebox, "border_width_left", target.border_width_left, tween_time)#func _input(event : InputEvent): func _unhandled_input(event: InputEvent) -> void: if in_context(): if shortcut and shortcut.matches_event(event): # let other CogitoButtons know that the current context has had a shortcut used used_shortcut = true elif used_shortcut and accepts_contextual_enter and event.is_action_pressed("ui_accept"): accept_event() press_button_manually()
func _on_pressed(): pressed_string.emit(text)
- Assistant
The
CogitoUiButtonclass you've provided is a custom button class in Godot that extends the built-inButtonclass. This class includes features such as style tweening when pressed, handling focus events, and integrating contextual shortcut acceptance.Overview of Key Components
-
Signals:
pressed_string(text: String): Emits a signal when the button is pressed, sending the associated text.
-
Variables:
tween_time: Specifies the duration for the tween effects.tween_stylebox: A style box used for tweening.styleboxes: A dictionary to store different style boxes based on states (normal, hover, pressed, etc.).current_state: Holds the current draw state of the button.accepts_contextual_enter: This allows the button to respond to UI context enter keys.used_shortcut: Tracks whether a shortcut has been used in the current context.tween: The tween instance used for tweening effect transitions.
-
Functions:
- Various functions are implemented to handle button behavior, including transitioning when the button is pressed, hovered, focused, and released.
Suggested Improvements
-
Code Clarity:
- Add more inline comments and documentation to clarify what each function and major step does.
-
Error Handling:
- Ensure that all user inputs and UI context checks handle potential errors such as null references.
-
Performance:
- Consider using a single tweening instance to reduce object creation if the tweens are sequential.
-
Avoiding Magic Numbers:
- Consider defining constants for easily changed values like tween duration and ease type settings.
-
Remove Redundant Code:
- Combine repeated code patterns, especially for tweening styles, into reusable functions to reduce redundancy.
Here’s a refactored version of your
CogitoUiButtonclass incorporating the above suggestions:extends Button class_name CogitoUiButton signal pressed_string(text: String) var tween_time: float = 0.2 var tween_stylebox: StyleBoxFlat var styleboxes: Dictionary = {} var current_state: int = BaseButton.DRAW_NORMAL # Accepts UI enter keys when other shortcuts have been used in context @export var accepts_contextual_enter: bool = false static var used_shortcut: bool = false var tween: Tween func _ready() -> void: # Connect signals for button interactions self.focus_entered.connect(_on_focus_entered) self.focus_exited.connect(_on_focus_exited) self.pressed.connect(_on_pressed) # Duplicate the normal stylebox to use as a base for tweening tween_stylebox = get_theme_stylebox('normal').duplicate() _setup_styleboxes() # Override styleboxes with the tween stylebox _set_stylebox_overrides() func _setup_styleboxes() -> void: # Store different styleboxes for various states styleboxes[BaseButton.DRAW_NORMAL] = get_theme_stylebox('normal').duplicate() styleboxes[BaseButton.DRAW_HOVER] = get_theme_stylebox('hover').duplicate() styleboxes[BaseButton.DRAW_PRESSED] = get_theme_stylebox('pressed').duplicate() styleboxes[BaseButton.DRAW_HOVER_PRESSED] = get_theme_stylebox('pressed').duplicate() styleboxes[BaseButton.DRAW_DISABLED] = get_theme_stylebox('disabled').duplicate() func _set_stylebox_overrides() -> void: # Set theme styleboxes for various button states add_theme_stylebox_override('normal', tween_stylebox) add_theme_stylebox_override('hover', tween_stylebox) add_theme_stylebox_override('focus', tween_stylebox) add_theme_stylebox_override('pressed', tween_stylebox) add_theme_stylebox_override('disabled', tween_stylebox) func press_button_manually() -> void: pressed.emit() # Kill any running tween and create a new one _stop_tween() tween = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC).set_parallel() _tween_stylebox_properties(styleboxes[BaseButton.DRAW_PRESSED]) func _process(_delta: float) -> void: # Check if the button's draw mode changed if get_draw_mode() != current_state: current_state = get_draw_mode() _stop_tween() _tween_stylebox_properties(styleboxes[current_state]) func _on_focus_entered() -> void: used_shortcut = false # Reset shortcut status on focus change _stop_tween() _tween_stylebox_properties(styleboxes[BaseButton.DRAW_HOVER]) func _on_focus_exited() -> void: if get_viewport().gui_get_focus_owner() == null: used_shortcut = false # Lost focus completely _stop_tween() _tween_stylebox_properties(styleboxes[BaseButton.DRAW_NORMAL]) func _tween_stylebox_properties(target_stylebox: StyleBoxFlat) -> void: # Tween the properties of the tween stylebox to match the target stylebox tween.tween_property(tween_stylebox, "bg_color", target_stylebox.bg_color, tween_time) tween.tween_property(tween_stylebox, "border_color", target_stylebox.border_color, tween_time) tween.tween_property(tween_stylebox, "border_width_left", target_stylebox.border_width_left, tween_time) func _stop_tween() -> void: # Kills the running tween if it exists if tween and tween.is_running(): tween.kill() func in_context() -> bool: var context = get_viewport().gui_get_focus_owner() if context: var context_owner = context.shortcut_context or context.get_parent_control() var our_context = shortcut_context or get_parent_control() return context_owner == our_context return false func _unhandled_input(event: InputEvent) -> void: if in_context(): if shortcut and shortcut.matches_event(event): # Let other CogitoButtons know that the current context used a shortcut used_shortcut = true elif used_shortcut and accepts_contextual_enter and event.is_action_pressed("ui_accept"): accept_event() press_button_manually() func _on_pressed() -> void: pressed_string.emit(text)Key Improvements Made:
-
Modularized Code: Repetitive code for setting up tween properties has been encapsulated into the
_tween_stylebox_propertiesfunction for reuse. -
Improved Comments: Enhanced comments throughout to explain functionality and intent.
-
Function Naming Consistency: Suffixing functions with a
_indicates that it is a private helper function, which is a common convention. -
Unified Tween Stop Logic: Created a single
_stop_tweenfunction to handle stopping running tweens. -
Simplified Context Checking: Cleaned up the logic for shortcut context checking for better readability.
These revisions maintain the original functionality while improving code quality, clarity, and maintainability in your custom button class.
-
- User
extends PanelContainer
@onready var wieldable_icon: TextureRect = MarginContainer/VBoxContainer/WieldableData/WieldableChargeLabel @onready var ammo_icon: TextureRect = MarginContainer/VBoxContainer/AmmoData/AmmoLabel
@onready var ammo_data: HBoxContainer = $MarginContainer/VBoxContainer/AmmoData
Called when the node enters the scene tree for the first time.
func _ready() -> void: pass # Replace with function body.
Function to update the displayed numbers and icons
func update_wieldable_data(wieldable_item: WieldableItemPD, _carried_ammo:int, _ammo_item: AmmoItemPD): if wieldable_item.wieldable_data_icon: wieldable_icon.texture = wieldable_item.wieldable_data_icon else: wieldable_icon.texture = wieldable_item.icon
if wieldable_item.no_reload: wieldable_charge_label.text = "" else: wieldable_charge_label.text = str(int(wieldable_item.charge_current)) # Hides ammo data ui elements if player doesn't have any ammo in their inventory (or if wieldable doesn't use ammo) if _ammo_item: ammo_data.show() ammo_icon.texture = _ammo_item.icon ammo_label.text = str(_carried_ammo) else: ammo_data.hide() - Assistant
Your provided code implements a user interface component in Godot, specifically a
PanelContainer, that displays information about wieldable items and ammo in the game. The component updates its UI elements based on the currently equipped wieldable item and the player's ammo status.Overview of Key Components:
-
Nodes:
wieldable_icon: Displays the icon for the currently wielded item.wieldable_charge_label: Shows the current charge or use state of the wieldable item.ammo_icon: Displays the icon for the ammo type the player currently has.ammo_label: Displays the amount of currently carried ammo.ammo_data: A container for holding ammo-related UI elements.
-
Functions:
_ready(): An initialization function that can set up the panel (currently has no implemented functionality).update_wieldable_data(wieldable_item: WieldableItemPD, _carried_ammo: int, _ammo_item: AmmoItemPD): Updates the UI elements based on the provided wieldable item and ammo data.
Suggested Improvements
-
Initialization:
- Implement the
_ready()function to set up initial states for your UI elements if needed (e.g., hiding elements initially or setting default textures).
- Implement the
-
Use of Constants:
- Consider using constants for the empty strings to improve readability and to avoid magic values in the update logic.
-
Error Handling:
- Include checks to handle potential null references, especially when accessing properties of
wieldable_itemand_ammo_item.
- Include checks to handle potential null references, especially when accessing properties of
-
Data Types:
- Ensure the input parameters are correctly typed (e.g., if
_carried_ammocan only be a non-negative integer, you might want to validate it).
- Ensure the input parameters are correctly typed (e.g., if
-
Improved Comments:
- Add comments to the logic in
update_wieldable_data()to clarify what the code does by explaining the logic behind certain conditions.
- Add comments to the logic in
Here’s an improved version of your class:
extends PanelContainer @onready var wieldable_icon: TextureRect = $MarginContainer/VBoxContainer/WieldableData/WieldableIcon @onready var wieldable_charge_label: Label = $MarginContainer/VBoxContainer/WieldableData/WieldableChargeLabel @onready var ammo_icon: TextureRect = $MarginContainer/VBoxContainer/AmmoData/AmmoIcon @onready var ammo_label: Label = $MarginContainer/VBoxContainer/AmmoData/AmmoLabel @onready var ammo_data: HBoxContainer = $MarginContainer/VBoxContainer/AmmoData # Called when the node enters the scene tree for the first time. func _ready() -> void: # Optionally clear initial values or set defaults for UI elements # e.g., hide ammo data initially or reset values ammo_data.hide() wieldable_charge_label.text = "" # Function to update the displayed numbers and icons func update_wieldable_data(wieldable_item: WieldableItemPD, _carried_ammo: int, _ammo_item: AmmoItemPD) -> void: # Set the wieldable item's icon wieldable_icon.texture = wieldable_item.wieldable_data_icon if wieldable_item.wieldable_data_icon else wieldable_item.icon # Update charge label; show empty string if no reload is allowed wieldable_charge_label.text = "" if wieldable_item.no_reload else str(int(wieldable_item.charge_current)) # Update ammo data UI; show it if player has ammo if _ammo_item and _carried_ammo > 0: ammo_data.show() ammo_icon.texture = _ammo_item.icon ammo_label.text = str(_carried_ammo) else: ammo_data.hide()Key Adjustments Made:
-
Implemented
_ready(): A simple initial setup to hide the ammo data UI and clear the charge label at the start. You can expand this based on your UI design needs. -
Improved Logic Clarity: Used ternary operators for setting the
wieldable_icontexture and made conditions more clear. -
Simplified Conditions: Added a check for
_carried_ammobeing greater than zero to ensure you only show the ammo data when the player has ammo available. -
Formatted Readability: Cleaned up some of the conditions and added comments to enhance readability and understanding.
These changes improve both the usability and maintainability of the user interface component as part of your game's HUD or inventory system.
-
- User
extends Node
If checked, the player will receive notifications when a quest status has changed.
@export var send_quest_notifications : bool
Reference to how a single quest is displayed in the QuestHUD
@export var quest_entry : PackedScene
@onready var quest_display: PanelContainer = $QuestDisplay
Quest groups:
@onready var active_group: VBoxContainer = QuestDisplay/VBoxContainer/TabContainer/Completed @onready var failed_group: VBoxContainer = $QuestDisplay/VBoxContainer/TabContainer/Failed
var player_hud #Reference of main Player HUD.
func _ready(): CogitoQuestManager.quest_activated.connect(_on_quest_activated) CogitoQuestManager.quest_completed.connect(_on_quest_completed) CogitoQuestManager.quest_failed.connect(_on_quest_failed) CogitoQuestManager.quest_updated.connect(_on_quest_updated) player_hud = get_parent()
#Hooking up quest display to player inventory toggle. player_hud.show_inventory.connect(_show_quest_display) player_hud.hide_inventory.connect(_hide_quest_display) quest_display.hide()func _show_quest_display(): update_active_quests() update_completed_quests() update_failed_quests() quest_display.show()
func _hide_quest_display(): quest_display.hide()
func update_active_quests(): #Clearing out group entries: for node in active_group.get_children(): node.queue_free()
for quest in CogitoQuestManager.get_active_quests(): var instanced_quest_entry = quest_entry.instantiate() active_group.add_child(instanced_quest_entry) instanced_quest_entry.set_quest_info(quest.quest_title,quest.quest_description,str(quest.quest_counter_current) + "/" + str(quest.quest_counter_goal))func update_completed_quests(): #Clearing out group entries: for node in completed_group.get_children(): node.queue_free()
for quest in CogitoQuestManager.get_completed_quests(): var instanced_quest_entry = quest_entry.instantiate() completed_group.add_child(instanced_quest_entry) instanced_quest_entry.set_quest_info(quest.quest_title,quest.quest_description,str(quest.quest_counter_current) + "/" + str(quest.quest_counter_goal))func update_failed_quests(): #Clearing out group entries: for node in failed_group.get_children(): node.queue_free()
for quest in CogitoQuestManager.get_failed_quests(): var instanced_quest_entry = quest_entry.instantiate() failed_group.add_child(instanced_quest_entry) instanced_quest_entry.set_quest_info(quest.quest_title,quest.quest_description,str(quest.quest_counter_current) + "/" + str(quest.quest_counter_goal))Called when the node enters the scene tree for the first time.
func _on_set_quest_notification(passed_quest_icon, passed_quest_text): if send_quest_notifications: player_hud._on_set_hint_prompt(passed_quest_icon,passed_quest_text)
func _on_quest_activated(_passed_quest:CogitoQuest): _on_set_quest_notification(null, str("Quest started: " + _passed_quest.quest_title))
func _on_quest_completed(_passed_quest:CogitoQuest): _on_set_quest_notification(null, str("Quest completed: " + _passed_quest.quest_title))
func _on_quest_failed(_passed_quest:CogitoQuest): _on_set_quest_notification(null, str("Quest failed: " + _passed_quest.quest_title))
func _on_quest_updated(_passed_quest:CogitoQuest): _on_set_quest_notification(null, str("Quest udpated: " + _passed_quest.quest_title))
- Assistant
The provided script represents a quest management UI in Godot that allows players to view active, completed, and failed quests in the game. It connects to a quest manager to receive notifications about quest status changes and updates its display accordingly.
Overview of Key Components
-
Export Variables:
send_quest_notifications: A boolean to determine if quest notifications are sent to the player.quest_entry: APackedScenethat defines how a single quest is displayed in the UI.
-
Node References:
quest_display: The main container for displaying quests.active_group,completed_group,failed_group: UI containers for organizing quests based on their statuses.player_hud: A reference to the player HUD that can have its inventory shown or hidden.
-
Functions:
_ready(): Initializes the quest display, sets up signal connections, and hides the quest display initially._show_quest_display(): Updates the quest display with active, completed, and failed quests and shows the display._hide_quest_display(): Hides the quest display.update_active_quests(),update_completed_quests(),update_failed_quests(): Functions that manage the display of quests in the respective containers by instantiating quest entries and updating them with quest information.
-
Quest Notification Handling:
- The script handles various quest events (activated, completed, failed, updated) and sends notifications to the player HUD.
Suggested Improvements
-
Performance Optimization:
- Instead of calling
queue_free()on each child node, consider clearing the container withclear()or using a mechanism to keep instances around if they might be needed later.
- Instead of calling
-
Error Handling:
- You may want to add checks to ensure scene instances are correctly created and handled, particularly in the quest entry setup.
-
Code Cleanliness:
- Combine similar functions for updating quests into a single function that takes the target group and the list of quests, reducing redundancy.
-
Organizational Structure:
- Add inline comments for clarity on how data flows through the script and enhances readability.
-
Notification Improvements:
- Define a clear structure for notifications, possibly using a dictionary to encapsulate related information rather than duplicating call signatures.
Here’s the improved version of your script with these considerations:
extends Node ## If checked, the player will receive notifications when a quest status has changed. @export var send_quest_notifications: bool ## Reference to how a single quest is displayed in the QuestHUD @export var quest_entry: PackedScene @onready var quest_display: PanelContainer = $QuestDisplay # Quest groups @onready var active_group: VBoxContainer = $QuestDisplay/VBoxContainer/TabContainer/Active @onready var completed_group: VBoxContainer = $QuestDisplay/VBoxContainer/TabContainer/Completed @onready var failed_group: VBoxContainer = $QuestDisplay/VBoxContainer/TabContainer/Failed var player_hud # Reference of main Player HUD. func _ready() -> void: # Connect signals from the quest manager CogitoQuestManager.quest_activated.connect(_on_quest_activated) CogitoQuestManager.quest_completed.connect(_on_quest_completed) CogitoQuestManager.quest_failed.connect(_on_quest_failed) CogitoQuestManager.quest_updated.connect(_on_quest_updated) player_hud = get_parent() # Hook up quest display to player inventory toggle player_hud.show_inventory.connect(_show_quest_display) player_hud.hide_inventory.connect(_hide_quest_display) quest_display.hide() func _show_quest_display() -> void: update_quests() # Update quest displays for all statuses quest_display.show() func _hide_quest_display() -> void: quest_display.hide() func update_quests() -> void: update_quest_group(active_group, CogitoQuestManager.get_active_quests()) update_quest_group(completed_group, CogitoQuestManager.get_completed_quests()) update_quest_group(failed_group, CogitoQuestManager.get_failed_quests()) func update_quest_group(group: VBoxContainer, quests: Array) -> void: # Clear existing entries in the group group.clear() # Clear all children in the container for quest in quests: if quest: var instanced_quest_entry = quest_entry.instantiate() group.add_child(instanced_quest_entry) instanced_quest_entry.set_quest_info(quest.quest_title, quest.quest_description, str(quest.quest_counter_current) + "/" + str(quest.quest_counter_goal)) # Called when the node enters the scene tree for the first time. func _on_set_quest_notification(passed_quest_icon, passed_quest_text) -> void: if send_quest_notifications: player_hud._on_set_hint_prompt(passed_quest_icon, passed_quest_text) func _on_quest_activated(_passed_quest: CogitoQuest): _on_set_quest_notification(null, str("Quest started: " + _passed_quest.quest_title)) func _on_quest_completed(_passed_quest: CogitoQuest): _on_set_quest_notification(null, str("Quest completed: " + _passed_quest.quest_title)) func _on_quest_failed(_passed_quest: CogitoQuest): _on_set_quest_notification(null, str("Quest failed: " + _passed_quest.quest_title)) func _on_quest_updated(_passed_quest: CogitoQuest): _on_set_quest_notification(null, str("Quest updated: " + _passed_quest.quest_title))Key Adjustments Made:
-
Unified Quest Updates: A single function
update_quests()combines the updates of different quest states (active, completed, failed) and uses a helper functionupdate_quest_group()to eliminate redundancy. -
Use of
clear()Method: Usedclear()on theVBoxContainerto remove all children instead of callingqueue_free()individually, which is more efficient and cleaner. -
Improved Comments: Added comments throughout the script for better understanding of functionality and data flow.
-
Error Handling: Ensured that each quest is checked before instantiation.
With these enhancements, your quest management UI should be more efficient and maintainable, improving overall performance and clarity.
-