@icon("res://addons/cogito/Assets/Graphics/Editor/IconCogitoSittable.svg") extends…
- User
@icon("res://addons/cogito/Assets/Graphics/Editor/Icon_CogitoSittable.svg") extends Node3D class_name CogitoSittable
signal object_state_updated(interaction_text: String) #used to display correct interaction prompts signal player_sit_down() signal player_stand_up()
#region Variables
@export var is_sat_on_start: bool = false ##Is this Sittable static or a Physics object? @export var physics_sittable: bool = false ##Interaction text when Sat Down @export var interaction_text_when_on : String = "Stand Up" ##Interction text when not Sat Down @export var interaction_text_when_off : String = "Sit"
@export_category("Sittable Behaviour") ##Area in which the Sitable can be interacted with @export var sit_area_behaviour: SitAreaBehaviour = SitAreaBehaviour.MANUAL ##Where should player be placed on Sittable exit @export var placement_on_leave: PlacementOnLeave = PlacementOnLeave.ORIGINAL ##Disable interaction while player is in the air @export var disable_on_jump: bool = true ##Disable interaction while player is in the Crouching @export var disable_on_crouch: bool = true ##Disables child Carryable Component if found, prevents Carrying sat on Chair @export var disable_carry : bool = true ##Should the player get ejected from the seat if it falls beyond eject_angle? @export var eject_on_fall: bool = false ##What angle should the player get ejected from Seat at? Also used to define fallen chair angle, to prevent interaction with fallen chairs @export var eject_angle: float = 45
@export_group("Vision") ##Players maximum Horizontal Look angle in either direction when Sitting @export var horizontal_look_angle: float = 120 ##Players maximum Vertical Look angle in either direction when Sitting @export var vertical_look_angle: float = 90 ##Height to lower Sit marker by, to account for the difference between player head and body height @export var sit_marker_displacement: float = 0.7
@export_group("Animation") ##Move the player to the Sit marker location using a Tween @export var tween_to_location : bool = true ##Make the player look at the look marker. Required for Limited look angles @export var tween_to_look_marker : bool = true ##Length of time player tweens into seat @export var tween_duration: float = 0.8 ##Time for rotation tween to face Look marker @export var rotation_tween_duration: float = 0.4 ##Name of animation in the Animation player node, to play on enter @export var animation_on_enter: String ##Name of animation in the Animation player node, to play on leave @export var animation_on_leave: String
@export_group("Audio") @export var sit_sound : AudioStream @export var stand_sound : AudioStream @export var sit_pitch : float = 0.5 @export var stand_pitch : float = 0.5
- Assistant
The code snippet provided is a Godot script written in GDScript, which focuses on creating a "sittable" object within a 3D environment. The
CogitoSittableclass controls the behavior of objects that players can sit on, including various settings and signals for managing interactions.Here’s a breakdown of the main components of the script:
Class Definition
- @icon: This attribute sets the icon for the class in the Godot editor.
- extends Node3D: Indicates that this class is extending Node3D, meaning it can be placed in the 3D scene hierarchy.
- class_name CogitoSittable: Declares the class name, making it available for instantiation in Godot.
Signals
Signals are a way to communicate between objects in Godot. In this script:
object_state_updated(interaction_text: String): This signal is emitted when the object's state changes and is used to update interaction prompts.player_sit_down(): Emitted when the player sits down on the object.player_stand_up(): Emitted when the player stands up from the object.
Export Variables
The
@exportkeyword allows these properties to be editable in the Godot editor:-
State Initialization
is_sat_on_start: Whether the object is considered sat on at the start.
-
Physics and Interaction Settings
physics_sittable: Determines if the sittable object is a physics object.interaction_text_when_on: Text displayed when the player is seated.interaction_text_when_off: Text displayed when the player is standing.
-
Sittable Behavior
sit_area_behaviour: Determines how interaction with the sittable area is managed.- Various boolean flags: Control factors like whether interaction is allowed when jumping or crouching, and the presence of carryable objects.
-
Ejection Settings
eject_on_fall: Determines whether players get ejected if the object tilts too far.eject_angle: Defines the angle for ejection and interaction prevention.
Vision Settings
- Look Angles: Variables define maximum angles for player view while sitting, ensuring a natural camera perspective.
- Sit Marker Displacement: Adjusts the position of the sit marker based on player model size.
Animation Settings
- Tween Settings: Control if and how the player moves to the sit position, including animation timings.
- Animation Names: Specifies which animations to play when the player sits down or stands up.
Audio Settings
- Sound Effects: Allows assignment of audio streams for sitting and standing actions, along with pitch modulation.
Additional Considerations
When implementing the functionality in this script, you would typically also manage player input and interactions, object animations, sound effects for transitions, and other game-related logic to ensure a seamless experience when players interact with the sittable objects.
Usage
This script would be attached to Node3D objects in a Godot project, and by configuring the export variables in the Godot Editor, developers can easily customize the behavior of different sittable objects throughout their game.
- User
@export_group("Nodes") ##Node used as the Sit marker, Defines Player location when sitting @export var sit_position_node_path: NodePath ##Node used as the Look marker, Defines centre of vision when sitting @export var look_marker_node_path: NodePath ##Area in which the Sitable can be interacted with @export var sit_area_node_path: NodePath
Node used to place player when Placement leave behaviour tells it to
@export var leave_node_path: NodePath ##Animation player node @export var animation_player_node_path: NodePath
@export_group("Interaction") ##Time before player can interact again. To prevent Spam which can cause issues with the player movement @export var interact_cooldown_duration = 0.4 ##Enable this node on sit (useful for enabling collision shapes) @export var enable_on_sit: Node
Nodes that will become visible when switch is ON. These will hide again when switch is OFF.
@export var nodes_to_show_when_on : Array[Node]
Nodes that will become hidden when switch is ON. These will show again when switch is OFF.
@export var nodes_to_hide_when_on : Array[Node]
Nodes that will have their interact function called when this is used.
@export var objects_call_interact : Array[NodePath] @export var objects_call_delay : float = 0.0
enum SitAreaBehaviour { MANUAL, ## Player needs to interact manually AUTO, ## Player sits automatically on entry NONE ## Player can interact from outside Sit Area }
enum PlacementOnLeave { ORIGINAL, ## Player returns to original location AUTO, ## Attempt to find nearby available location for Player using Navmesh - Experimental TRANSFORM, ## Player is placed at defined Leave node Make sure this is setup in Nodes section DISPLACEMENT ## The displacement between player and Sittable is taken on sit down, and used on standup relative to Sittables new location }
@onready var audio_stream_player_3d = BasicInteraction
var is_occupied: bool = false var occupant_id: String = "" var interaction_text : String var sit_position_node: Node3D = null var look_marker_node: Node3D = null var animation_player: AnimationPlayer var original_position: Transform3D
var interaction_nodes : Array[Node] var carryable_components: Array = [Node] var player_node: Node3D = null var player_in_sit_area: bool = false var cogito_properties : CogitoProperties = nullvar interaction_component_state:bool = false #endregion
- Assistant
In this part of the script, additional properties, variables, and enumerations are defined for the
CogitoSittableclass in Godot. These properties enhance the functionality related to player interactions with the sittable object, as well as manage nodes related to the sitting process.Node Definitions
This section primarily deals with defining NodePaths, which allow the script to reference various nodes in the scene tree for functionality:
-
Sit and Look Markers:
sit_position_node_path: Path to the node that defines where the player will sit.look_marker_node_path: Path to the node that defines where the player will look.
-
Interaction Area:
sit_area_node_path: Path to the node that defines the interaction area.
-
Player Placement Nodes:
leave_node_path: Path to the node where the player should be placed when leaving.
-
Animation Control:
animation_player_node_path: Path to the node controlling animations.
Interaction Properties
Properties related to the interaction mechanics of the sittable object:
-
Cooldown and Enable Mechanics:
interact_cooldown_duration: Sets a cooldown duration to prevent spamming of the sit interaction.enable_on_sit: A node that can be enabled when the player sits down.
-
Visibility Control:
nodes_to_show_when_on: Nodes that will become visible when the sittable is activated.nodes_to_hide_when_on: Nodes that will be hidden when the sittable is activated.
-
Interactivity Components:
objects_call_interact: An array of nodes that will have an interact function called.objects_call_delay: A delay before calling the interact function on the aforementioned nodes.
Enumerations
Two enums are defined to provide readability and clear options for controlling behavior:
-
SitAreaBehaviour: This enum defines how the player can interact with the sittable area:
MANUAL: Requires manual interaction from the player.AUTO: Player automatically sits when entering the area.NONE: Allows interaction from outside the sit area.
-
PlacementOnLeave: This enum specifies how the player will be positioned when leaving the sittable:
ORIGINAL: Player returns to their original location before sitting.AUTO: Attempts to find a nearby spot using navigation mesh functionality.TRANSFORM: Moves the player to a defined leave node.DISPLACEMENT: Takes the displacement of the player when they sit down and applies it when they stand up, adjusting for any movement of the sittable.
Variables and Components
Several variables are defined to manage the state and behavior of the sittable object:
-
Node References:
audio_stream_player_3d: A reference to the 3D audio player node for playing sounds.BasicInteraction: A reference to a node handling basic interactions, likely a script or component.
-
Occupancy Tracking:
is_occupied: A boolean flag indicating if the sittable is currently occupied.occupant_id: A string to hold an identifier for the current occupant (likely the player).
-
Interaction Management:
interaction_text: The text displayed for interactions.sit_position_node,look_marker_node, andanimation_player: Variables to store node references for easier use.
-
Transformations:
original_position: Stores the original position of the sittable for return logic.
-
Runtime Arrays:
interaction_nodes: An array to handle various nodes related to interaction.carryable_components: An array for tracking any carryable components connected to the sittable.
-
Player State:
player_node: A reference to the player node for integration.player_in_sit_area: A flag to check if the player is within the sit area.cogito_properties: A reference to an object holding additional properties related to interactions.
-
Interaction State:
interaction_component_state: A boolean flag to control the state of interactions dynamically.
Summary
This portion of the code provides a strong foundation for managing player interactions with sittable objects, managing node paths, visibility, and interactions. It enables developers to add extra functionality and control the behavior of the interaction in a structured manner. The use of enumerations for behavior types adds clarity and reduces the chance of errors when managing seating logic.
Overall, with these additions,
CogitoSittablebecomes a robust class for handling various interaction scenarios in a game developed with Godot. -
- User
func _ready(): #find player node player_node = CogitoSceneManager._current_player_node self.add_to_group("interactable") add_to_group("save_object_state") interaction_nodes = find_children("","InteractionComponent",true) #Grabs all attached interaction components interaction_component_state = false # set interaction component to disabled on startup #find sit position node sit_position_node = get_node_or_null(sit_position_node_path) if not sit_position_node: print("Sit position node not found. Ensure the path is correct.") else: displace_sit_marker()
# find the look marker node look_marker_node = get_node_or_null(look_marker_node_path) if not look_marker_node: CogitoGlobals.debug_log(true, "cogito_sittable", "Look marker node not found.") #find optional animation player node animation_player = get_node_or_null(animation_player_node_path) match sit_area_behaviour: SitAreaBehaviour.MANUAL: BasicInteraction.is_disabled = true SitAreaBehaviour.MANUAL: BasicInteraction.is_disabled = true SitAreaBehaviour.NONE: BasicInteraction.is_disabled = false if disable_carry: carryable_components = get_child_carryable_components() if is_sat_on_start: interact(player_node.player_interaction_component) BasicInteraction.is_disabled = false find_cogito_properties() - Assistant
The
_ready()function in Godot is a built-in callback that is executed when a node and its children have entered the scene tree, making it an ideal place for initialization tasks. The following is a breakdown of what is happening in the provided_ready()function for theCogitoSittableclass:Breakdown of the
_ready()Function-
Player Node Retrieval:
player_node = CogitoSceneManager._current_player_nodeThis line retrieves the current player node from the
CogitoSceneManager, allowing the script to interact with the player's node for behavior and interactions. -
Add to Groups:
self.add_to_group("interactable") add_to_group("save_object_state")Here, the instance is added to two groups:
"interactable": This may be used to identify all interactable objects in the scene."save_object_state": This group probably helps with saving relevant states of objects throughout the game.
-
Finding Interaction Components:
interaction_nodes = find_children("","InteractionComponent",true)This line searches for all child nodes in the current node that match the name
"InteractionComponent"and adds them to theinteraction_nodesarray. Thetrueparameter allows searching through the entire subtree. -
Initialize Interaction Component State:
interaction_component_state = falseThis sets the interaction component state to disabled at the start.
-
Finding the Sit Position Node:
sit_position_node = get_node_or_null(sit_position_node_path) if not sit_position_node: print("Sit position node not found. Ensure the path is correct.") else: displace_sit_marker()The function attempts to retrieve the sit position node using the specified
NodePath. If the node cannot be found, a message is printed to the output. If found, thedisplace_sit_marker()function is called to appropriately position the sitting marker. -
Finding the Look Marker Node:
look_marker_node = get_node_or_null(look_marker_node_path) if not look_marker_node: CogitoGlobals.debug_log(true, "cogito_sittable", "Look marker node not found.")Similar to the sit position node, this retrieves the look marker node and logs a debug message if it is not found.
-
Finding the Animation Player Node:
animation_player = get_node_or_null(animation_player_node_path)An optional animation player node is fetched if specified.
-
Setting Basic Interaction State Based on Sit Area Behaviour:
match sit_area_behaviour: SitAreaBehaviour.MANUAL: BasicInteraction.is_disabled = true SitAreaBehaviour.NONE: BasicInteraction.is_disabled = falseA
matchstatement is used to set the state of the basic interaction based on thesit_area_behaviourenum:- If set to
MANUAL, interaction is disabled since the player must manually initiate sitting. - If set to
NONE, interaction is enabled to allow external sitting.
- If set to
-
Handling Carryable Components:
if disable_carry: carryable_components = get_child_carryable_components()If the
disable_carryflag is set totrue, potential carryable components that are children of the sittable object are fetched. -
Interacting on Start:
if is_sat_on_start: interact(player_node.player_interaction_component) BasicInteraction.is_disabled = falseIf the
is_sat_on_startis true, it immediately invokes theinteractmethod on the player's interaction component, simulating the player being seated from the start. TheBasicInteractionis then enabled. -
Finding Cogito Properties:
find_cogito_properties()This function call is presumably used to gather additional properties or configurations related to the
CogitoSittableinstance, providing necessary game logic.
Summary
The
_ready()method initializes theCogitoSittableobject, ensuring that all necessary nodes for interaction are set up correctly. It manages player interactions based on various configurations, prepares child components, and retrieves essential nodes to support the functionality of the sittable object. This setup is crucial for ensuring that the interaction logic works seamlessly when players engage with the sittable object in the game. -
- User
func get_child_carryable_components() -> Array: var components = [] # iterate through child nodes and check for CogitoCarryableComponent for child in self.get_children(): if child is CogitoCarryableComponent: components.append(child) return components
func displace_sit_marker(): if sit_position_node: # Adjust the sit marker node downward based on sit_marker_displacement var adjusted_transform = sit_position_node.transform adjusted_transform.origin.y -= sit_marker_displacement sit_position_node.transform = adjusted_transform
func _sit_down():
if animation_player: animation_player.play(animation_on_enter) #sit down audio audio_stream_player_3d.stream = sit_sound audio_stream_player_3d.pitch_scale = sit_pitch audio_stream_player_3d.play() #update interaction text interaction_text = interaction_text_when_on object_state_updated.emit(interaction_text) #enable any enable on sit node if enable_on_sit: enable_on_sit.disabled = false # Disable carryable components if necessary if disable_carry: for component in carryable_components: component.is_disabled = true #show any show on sit node for node in nodes_to_show_when_on: node.show() for node in nodes_to_hide_when_on: node.hide() is_occupied = true - Assistant
The provided code snippet includes three functions that contribute to the functionality of the
CogitoSittableclass in a Godot game. Each function plays a distinct role in managing how the player interacts with the sittable object, particularly when sitting down and handling components associated with the object. Here’s a detailed breakdown of each function:1.
get_child_carryable_components()func get_child_carryable_components() -> Array: var components = [] # iterate through child nodes and check for CogitoCarryableComponent for child in self.get_children(): if child is CogitoCarryableComponent: components.append(child) return componentsPurpose:
This function retrieves all child nodes of the
CogitoSittablethat are instances ofCogitoCarryableComponent, effectively gathering a list of components that can be carried.Breakdown:
- A new array
componentsis initialized to store carryable components. - The function iterates through all child nodes of the
CogitoSittableobject. - For each child, it checks if that child is an instance of
CogitoCarryableComponent. - If true, the child node is appended to the
componentsarray. - Finally, the list of carryable components is returned.
2.
displace_sit_marker()func displace_sit_marker(): if sit_position_node: # Adjust the sit marker node downward based on sit_marker_displacement var adjusted_transform = sit_position_node.transform adjusted_transform.origin.y -= sit_marker_displacement sit_position_node.transform = adjusted_transformPurpose:
This function adjusts the position of the sitting marker node (where the player will be seated) by a specified downward displacement to account for differences in player height or other design considerations.
Breakdown:
- The function first checks if the
sit_position_nodeexists. - If it does, it retrieves the current transformation of the sit position node.
- The Y-component of the node's origin is decreased by the value of
sit_marker_displacement, effectively lowering the position. - The modified transformation is then assigned back to the
sit_position_node, thus updating its position.
3.
_sit_down()func _sit_down(): if animation_player: animation_player.play(animation_on_enter) # sit down audio audio_stream_player_3d.stream = sit_sound audio_stream_player_3d.pitch_scale = sit_pitch audio_stream_player_3d.play() # update interaction text interaction_text = interaction_text_when_on object_state_updated.emit(interaction_text) # enable any enable on sit node if enable_on_sit: enable_on_sit.disabled = false # Disable carryable components if necessary if disable_carry: for component in carryable_components: component.is_disabled = true # show any show on sit node for node in nodes_to_show_when_on: node.show() for node in nodes_to_hide_when_on: node.hide() is_occupied = truePurpose:
This function handles the logic when a player sits down on the sittable object. It plays animations, sounds, updates the state, and manages visibility for nodes based on the interaction.
Breakdown:
-
If there is an
animation_player, it plays the specified animation for sitting down (usinganimation_on_enter). -
Audio Playback:
- Sets the audio stream to the
sit_soundand adjusts its pitch using the specifiedsit_pitch. - Plays the sound using the
audio_stream_player_3d.
- Sets the audio stream to the
-
Interaction Text Update:
- Changes the
interaction_textto reflect that the player is now sitting, usinginteraction_text_when_on. - Emits the
object_state_updatedsignal to notify other components or systems that the interaction text has changed.
- Changes the
-
Enable Nodes:
- If
enable_on_sitis defined, this node is enabled (set to not disabled).
- If
-
Managing Carryable Components:
- If the
disable_carryflag is true, the function iterates through the previously collectedcarryable_componentsand sets theiris_disabledproperty to true, thereby disabling the ability to carry these items while seated.
- If the
-
Visibility Management:
- Iterates through the
nodes_to_show_when_onarray and shows those nodes (makes them visible). - Iterates through the
nodes_to_hide_when_onarray and hides those nodes (makes them invisible).
- Iterates through the
-
Finally, sets the
is_occupiedvariable totrue, marking the sittable object as currently in use.
Summary
These functions enhance the interactivity of the
CogitoSittableclass by managing the child's carryable components, adjusting seating marker positions, and defining the logic executed when the player sits down. Together, they create a robust system that can handle various player interactions, sound effects, and animations while ensuring the game remains responsive and intuitive. - A new array
- User
func _stand_up():
if animation_player: animation_player.play(animation_on_leave) #stand up audio audio_stream_player_3d.stream = stand_sound audio_stream_player_3d.pitch_scale = stand_pitch audio_stream_player_3d.play() #update interaction text interaction_text = interaction_text_when_off object_state_updated.emit(interaction_text) #disable any enable_on_sit node if enable_on_sit: enable_on_sit.disabled = true # Enable carryable components if necessary if disable_carry: for component in carryable_components: component.is_disabled = false #hide any show on sit node for node in nodes_to_show_when_on: node.hide() for node in nodes_to_hide_when_on: node.show() is_occupied = falsefunc switch(): if is_occupied: _stand_up() else: _sit_down()
func set_state(): #On loadet behaviour match sit_area_behaviour: SitAreaBehaviour.MANUAL: BasicInteraction.is_disabled = true SitAreaBehaviour.MANUAL: BasicInteraction.is_disabled = true SitAreaBehaviour.NONE: BasicInteraction.is_disabled = false
find_cogito_properties() #If the saved interaction state is true, override on load to avoid player getting stuck. Can ignore the reverse if interaction_component_state == true: BasicInteraction.is_disabled = false if is_occupied: _sit_down() else: _stand_up() - Assistant
The provided code snippet continues the functionality of the
CogitoSittableclass by implementing the logic for standing up, switching between sitting and standing states, and setting the state on game load. Here's a detailed breakdown of each function:1.
_stand_up()func _stand_up(): if animation_player: animation_player.play(animation_on_leave) # stand up audio audio_stream_player_3d.stream = stand_sound audio_stream_player_3d.pitch_scale = stand_pitch audio_stream_player_3d.play() # update interaction text interaction_text = interaction_text_when_off object_state_updated.emit(interaction_text) # disable any enable_on_sit node if enable_on_sit: enable_on_sit.disabled = true # Enable carryable components if necessary if disable_carry: for component in carryable_components: component.is_disabled = false # hide any show on sit node for node in nodes_to_show_when_on: node.hide() for node in nodes_to_hide_when_on: node.show() is_occupied = falsePurpose:
The
_stand_up()function handles the logic for the player when they stand up from the sittable object. It emphasizes reversing the changes made when the player sat down.Breakdown:
-
If an
animation_playerexists, it plays the specified animation for standing up (animation_on_leave). -
Audio Playback:
- Sets the audio stream to the stipulated
stand_soundand adjusts its pitch withstand_pitch. - Plays the sound using the
audio_stream_player_3d.
- Sets the audio stream to the stipulated
-
Interaction Text Update:
- Changes the
interaction_textto reflect that the player is no longer sitting, usinginteraction_text_when_off. - Emits the
object_state_updatedsignal to update the interaction prompt in the UI.
- Changes the
-
Node Management:
- If
enable_on_sitexists, this node is set to disabled (suggesting some optional functionality tied to being seated).
- If
-
Managing Carryable Components:
- If the flag
disable_carryis true, it iterates throughcarryable_componentsto re-enable them by setting theiris_disabledproperty to false.
- If the flag
-
Visibility Management:
- Hides nodes that were supposed to be shown when the player was sitting.
- Shows nodes that were supposed to be hidden when the player was sitting.
-
Finally, it sets
is_occupiedto false to indicate that no player is currently seated.
2.
switch()func switch(): if is_occupied: _stand_up() else: _sit_down()Purpose:
The
switch()function toggles the sitting and standing state of the player based on the current occupancy of the sittable object.Breakdown:
- This function checks if
is_occupiedis true. - If it is true,
_stand_up()is called to make the player stand. - If it is false,
_sit_down()is invoked to make the player sit down.
3.
set_state()func set_state(): # On loaded behaviour match sit_area_behaviour: SitAreaBehaviour.MANUAL: BasicInteraction.is_disabled = true SitAreaBehaviour.NONE: BasicInteraction.is_disabled = false find_cogito_properties() # If the saved interaction state is true, override on load to avoid player getting stuck if interaction_component_state == true: BasicInteraction.is_disabled = false if is_occupied: _sit_down() else: _stand_up()Purpose:
The
set_state()function manages the state of the sittable object upon loading, ensuring compatibility with saved game states and maintaining proper interactions.Breakdown:
-
A
matchstatement evaluates thesit_area_behaviour:- If it’s
MANUAL, interaction is set to disabled. - If it’s
NONE, interaction is enabled.
- If it’s
-
Finding Properties: It calls
find_cogito_properties()which likely retrieves or sets some properties related to this sittable object. -
An override check occurs for
interaction_component_state. If it is true, it ensures that interaction with the object is enabled, which is crucial for preventing the player from getting stuck. -
Finally, based on the
is_occupiedstate, it either calls_sit_down()or_stand_up(), ensuring that the object's state reflects the player’s initial condition when loaded.
Summary
These functions add crucial behavior to the
CogitoSittableclass, allowing players to transition smoothly between sitting and standing, managing audio cues and interaction states appropriately. The toggling function is particularly valuable for user experience, as it cleanly abstracts away state management into a single call. Theset_state()function serves to restore the object's state after loading a game, maintaining the continuity of gameplay and interaction fidelity. Together, these functions uphold the interactive and user-friendly nature of the sittable object in the game. -
- User
func _on_sit_area_body_entered(body): if body == player_node: player_in_sit_area = true
match sit_area_behaviour: SitAreaBehaviour.MANUAL: BasicInteraction.is_disabled = false interaction_component_state = true SitAreaBehaviour.AUTO: if not player_node.is_sitting: interact(player_node.player_interaction_component) BasicInteraction.is_disabled = false interaction_component_state = true SitAreaBehaviour.NONE: BasicInteraction.is_disabled = false interaction_component_state = truefunc _on_sit_area_body_exited(body): if body == player_node: player_in_sit_area = false if player_node.is_sitting: #don't disable interactable if the players sitting to avoid player getting stuck interaction_component_state = true BasicInteraction.is_disabled = false else: BasicInteraction.is_disabled = true interaction_component_state = false
func find_cogito_properties(): var property_nodes = find_children("","CogitoProperties",true) #Grabs all attached property components if property_nodes: cogito_properties = property_nodes[0]
var interact_cooldown = 0.0
- Assistant
The provided code snippet continues to define the behavior of the
CogitoSittableclass, handling player interactions related to entering and exiting a defined sitting area. It also includes a method to find and manage properties related to theCogitoSittableobject. Let's break down each function in detail.1.
_on_sit_area_body_entered(body)func _on_sit_area_body_entered(body): if body == player_node: player_in_sit_area = true match sit_area_behaviour: SitAreaBehaviour.MANUAL: BasicInteraction.is_disabled = false interaction_component_state = true SitAreaBehaviour.AUTO: if not player_node.is_sitting: interact(player_node.player_interaction_component) BasicInteraction.is_disabled = false interaction_component_state = true SitAreaBehaviour.NONE: BasicInteraction.is_disabled = false interaction_component_state = truePurpose:
This function is triggered when the player (or another body) enters the defined sit area. It checks whether the body is the player, and if so, modifies the interaction state based on the
sit_area_behaviour.Breakdown:
-
When the player enters the area,
player_in_sit_areais set totrue, tracking the player’s presence. -
A
matchstatement evaluates thesit_area_behaviour:-
MANUAL: Interaction is enabled (
BasicInteraction.is_disabled = false), allowing the player to sit down manually. Theinteraction_component_stateis updated to reflect this. -
AUTO: If the player is not already sitting (
not player_node.is_sitting), the code calls theinteractmethod on the player's interaction component to initiate sitting. Interaction is then enabled, and the component state is also updated. -
NONE: Interaction is enabled, and the component state is set to active.
-
2.
_on_sit_area_body_exited(body)func _on_sit_area_body_exited(body): if body == player_node: player_in_sit_area = false if player_node.is_sitting: # don't disable interactable if the player is sitting to avoid the player getting stuck interaction_component_state = true BasicInteraction.is_disabled = false else: BasicInteraction.is_disabled = true interaction_component_state = falsePurpose:
This function is invoked when the player exits the defined sitting area. It manages the interaction state accordingly.
Breakdown:
-
If the body exiting the area is the player,
player_in_sit_areais set tofalse. -
The function checks if the player is currently sitting:
-
If
player_node.is_sittingis true, it retains the active interaction state to avoid locking the player into the sitting position and keeps the interaction enabled. -
If the player is not sitting:
- Interaction is disabled, and the interaction component state is updated to reflect that, ensuring that the player can no longer initiate sitting while outside the area.
-
3.
find_cogito_properties()func find_cogito_properties(): var property_nodes = find_children("","CogitoProperties",true) # Grabs all attached property components if property_nodes: cogito_properties = property_nodes[0]Purpose:
This function searches for child nodes of the
CogitoSittableinstance that are of typeCogitoProperties. It stores a reference to the first matching property node.Breakdown:
-
The function searches for all child nodes named
"CogitoProperties"within this node and its children, creating a listproperty_nodes. -
If such nodes are found, it assigns the first instance to the
cogito_propertiesvariable.
4.
var interact_cooldown = 0.0This line declares a variable
interact_cooldown, which is initialized to0.0. While its functionality is not detailed in this part of the code, it suggests there may be a mechanism in the script to control how often the player can interact with the sittable object, preventing issues like rapid or repeated inputs during interactions (e.g., spamming the sit command).Summary
These functions provide essential features for managing player interactions with the sittable area:
-
Entering and Exiting Logic: The first two functions handle how the player interacts with the sittable area, allowing for both manual and automatic sitting based on the player's state and presence. They correctly manage interaction states to prevent issues when the player tries to sit or leave the sit area.
-
Property Management: The third function allows the script to find and store additional properties relevant to the sittable object, enhancing overall functionality.
Together, these implementations enhance the user experience by ensuring that interactions are context-aware and preventing glitches or unwanted behavior in gameplay.
-
- User
func interact(player_interaction_component):
#Prevent entering fallen chair if !is_occupied and _is_fallen(): player_interaction_component.send_hint(null, "I can't sit there!") return # Get the current time from the engine var current_time = Time.get_ticks_msec()/ 1000.0 # If cooldown hasn't passed, return early to prevent spamming if current_time < interact_cooldown: return # Reset cooldown to current time + duration interact_cooldown = current_time + interact_cooldown_duration if disable_on_crouch == true: if player_node.is_crouching: player_interaction_component.send_hint(null, "I should stand up first") return if disable_on_jump == true: if player_node.is_in_air: player_interaction_component.send_hint(null, "I should land first") return # If the player is already sitting in a seat, and interacts with that seat then stand if player_node.is_sitting and CogitoSceneManager._current_sittable_node == self: CogitoSceneManager.emit_signal("stand_requested") _stand_up() # If the player is already sitting in a seat, and interacts with a different seat then move seat elif player_node.is_sitting and CogitoSceneManager._current_sittable_node != self : var previous_seat = CogitoSceneManager._current_sittable_node previous_seat._stand_up() CogitoSceneManager._current_sittable_node = self CogitoSceneManager.emit_signal("seat_move_requested", self) _sit_down() # If the player is not in any seat, then sit down elif not player_node.is_sitting: CogitoSceneManager._current_sittable_node = self CogitoSceneManager.emit_signal("sit_requested", self) _sit_down() if !objects_call_interact: return for nodepath in objects_call_interact: await get_tree().create_timer(objects_call_delay).timeout if nodepath != null: var object = get_node(nodepath) object.interact(player_interaction_component)func _is_fallen() -> bool: var current_rotation = global_transform.basis.get_euler() var pitch_angle = rad_to_deg(abs(current_rotation.x)) var roll_angle = rad_to_deg(abs(current_rotation.z)) if pitch_angle > eject_angle or roll_angle > eject_angle: return true return false
func save(): var state_dict = { "node_path" : self.get_path(), "is_occupied" : is_occupied, "occupant_id" : occupant_id, "physics_sittable" : physics_sittable, "interaction_text" : interaction_text, "interaction_component_state" : interaction_component_state, "pos_x" : position.x, "pos_y" : position.y, "pos_z" : position.z, "rot_x" : rotation.x, "rot_y" : rotation.y, "rot_z" : rotation.z, "global_pos_x" : global_position.x, "global_pos_y" : global_position.y, "global_pos_z" : global_position.z,
} # If the node is a RigidBody3D, then save the physics properties of it var rigid_body = find_rigid_body() if rigid_body: state_dict["linear_velocity_x"] = rigid_body.linear_velocity.x state_dict["linear_velocity_y"] = rigid_body.linear_velocity.y state_dict["linear_velocity_z"] = rigid_body.linear_velocity.z state_dict["angular_velocity_x"] = rigid_body.angular_velocity.x state_dict["angular_velocity_y"] = rigid_body.angular_velocity.y state_dict["angular_velocity_z"] = rigid_body.angular_velocity.z return state_dictfunc find_rigid_body() -> RigidBody3D: var current = self while current: if current is RigidBody3D: return current as RigidBody3D current = current.get_parent() return null
- Assistant
The provided code snippet defines several functions related to the interaction capabilities of the
CogitoSittableclass in your Godot game. Here's a detailed breakdown of each function:1.
interact(player_interaction_component)func interact(player_interaction_component): # Prevent entering fallen chair if !is_occupied and _is_fallen(): player_interaction_component.send_hint(null, "I can't sit there!") return # Get the current time from the engine var current_time = Time.get_ticks_msec()/ 1000.0 # If cooldown hasn't passed, return early to prevent spamming if current_time < interact_cooldown: return # Reset cooldown to current time + duration interact_cooldown = current_time + interact_cooldown_duration if disable_on_crouch == true: if player_node.is_crouching: player_interaction_component.send_hint(null, "I should stand up first") return if disable_on_jump == true: if player_node.is_in_air: player_interaction_component.send_hint(null, "I should land first") return # If the player is already sitting in a seat, and interacts with that seat then stand if player_node.is_sitting and CogitoSceneManager._current_sittable_node == self: CogitoSceneManager.emit_signal("stand_requested") _stand_up() # If the player is already sitting in a seat, and interacts with a different seat then move seat elif player_node.is_sitting and CogitoSceneManager._current_sittable_node != self : var previous_seat = CogitoSceneManager._current_sittable_node previous_seat._stand_up() CogitoSceneManager._current_sittable_node = self CogitoSceneManager.emit_signal("seat_move_requested", self) _sit_down() # If the player is not in any seat, then sit down elif not player_node.is_sitting: CogitoSceneManager._current_sittable_node = self CogitoSceneManager.emit_signal("sit_requested", self) _sit_down() if !objects_call_interact: return for nodepath in objects_call_interact: await get_tree().create_timer(objects_call_delay).timeout if nodepath != null: var object = get_node(nodepath) object.interact(player_interaction_component)Purpose:
This function manages player interactions with the sittable object. It checks various conditions and handles sitting/standing functionality, cooldowns, and fall checks.
Breakdown:
-
Fall Check: The function first checks if the player is trying to interact with an object that is considered "fallen". If the object is not occupied and has fallen, it sends the player a hint saying they cannot sit there.
-
Cooldown Management: The function checks if a cooldown period has elapsed using the current game time. If the player attempts to interact before the cooldown ends, the function exits early.
-
Crouch and Jump Checks: If crouching or jumping is disabled, the function verifies the player's state and sends appropriate hints if they are in the wrong state.
-
Sitting Logic:
- If the player is already sitting on this specific seat and interacts again, they stand up.
- If the player is sitting on a different seat, the previous seat is checked, and they are made to stand up before sitting on the new seat.
- If the player is not sitting at all, they sit down on this seat.
-
Object Interaction: If there are any nodes in
objects_call_interact, the function iterates through them, creating a timer based onobjects_call_delaybefore calling theinteractmethod of each relevant object, allowing for the potential interaction with other nodes linked to the sittable.
2.
_is_fallen() -> boolfunc _is_fallen() -> bool: var current_rotation = global_transform.basis.get_euler() var pitch_angle = rad_to_deg(abs(current_rotation.x)) var roll_angle = rad_to_deg(abs(current_rotation.z)) if pitch_angle > eject_angle or roll_angle > eject_angle: return true return falsePurpose:
This function checks if the sittable object has fallen beyond a specified angle, determining if it is still usable.
Breakdown:
-
The function calculates the current rotations of the object and converts the pitch and roll angles from radians to degrees.
-
If either the pitch or roll exceeds the predefined
eject_angle, the function returnstrue, indicating the sittable has fallen.
3.
save()func save(): var state_dict = { "node_path" : self.get_path(), "is_occupied" : is_occupied, "occupant_id" : occupant_id, "physics_sittable" : physics_sittable, "interaction_text" : interaction_text, "interaction_component_state" : interaction_component_state, "pos_x" : position.x, "pos_y" : position.y, "pos_z" : position.z, "rot_x" : rotation.x, "rot_y" : rotation.y, "rot_z" : rotation.z, "global_pos_x" : global_position.x, "global_pos_y" : global_position.y, "global_pos_z" : global_position.z, } # If the node is a RigidBody3D, then save the physics properties of it var rigid_body = find_rigid_body() if rigid_body: state_dict["linear_velocity_x"] = rigid_body.linear_velocity.x state_dict["linear_velocity_y"] = rigid_body.linear_velocity.y state_dict["linear_velocity_z"] = rigid_body.linear_velocity.z state_dict["angular_velocity_x"] = rigid_body.angular_velocity.x state_dict["angular_velocity_y"] = rigid_body.angular_velocity.y state_dict["angular_velocity_z"] = rigid_body.angular_velocity.z return state_dictPurpose:
The
save()function collects relevant state data of the sittable object into a dictionary, which could be used for saving game state.Breakdown:
-
A dictionary
state_dictis created to store various properties of the object, including:- Node path, occupancy state, occupant ID, interaction text, position, rotation, etc.
-
It checks if the node is a
RigidBody3D. If it is, it adds the current linear and angular velocities to the dictionary. -
The function finally returns the
state_dict, providing a snapshot of the object's state that can be used for saving purposes.
4.
find_rigid_body() -> RigidBody3Dfunc find_rigid_body() -> RigidBody3D: var current = self while current: if current is RigidBody3D: return current as RigidBody3D current = current.get_parent() return nullPurpose:
This function searches up the node hierarchy to find and return the first
RigidBody3Dancestor of the current node, if it exists.Breakdown:
- The function starts from the current node and walks up the parent chain.
- If it finds a node that is a
RigidBody3D, it returns that node. - If it traverses the entire hierarchy without finding one, it returns
null.
Summary
These functions are essential for managing player interactions with sittable objects. They ensure:
- Interaction logic is sound and verifies conditions to avoid player frustrations (e.g., trying to sit on a fallen chair).
- The saving mechanism captures the state of the object effectively, allowing for game state persistence.
- The ergonomics of the game are maintained by checking for player states (crouching, jumping) before allowing interactions.
This overall structure leads to a robust interaction system that enhances player experience when interacting with sittable objects in the game.
-