it spam change the direction of the sprite when you move < 0 :
func _read_input():
var mouse_position = get_global_mouse_position()
var direction = (mouse_position - position).normalized()
if direction.x < 0:
scale.x = -1
else:
scale.x = 1
var movement = []
if Input.is_action_pressed("move_up"): movement.append("up")
if Input.is_action_pressed("move_down"): movement.append("down")
if Input.is_action_pressed("move_right"): movement.append("right")
if Input.is_action_pressed("move_left"): movement.append("left")
move.execute(self, movement)
if last_ability > global_cooldown:
if Input.is_action_just_pressed("interact"):
interact()
last_ability = 0
#if Input.is_action_just_pressed("ability_1"):
# fireball.execute(self)
# last_ability = 0
#if Input.is_action_just_pressed("inventory"):
# inventory.execute(self)
# last_ability = 0
Assistant
User
still spams left and right if you have the mouse on the left side
Assistant
If the sprite is flipping back and forth rapidly ("spamming") when the mouse is on the left side, it suggests that there is a logic error which is causing scale.x to rapidly toggle between -1 and 1. This could happen if there is conflicting input or updates that are continuously changing the direction.
The problem may stem from the fact that every frame in which is called, it's recalculating the direction based on the current mouse position and the position of the sprite. If the sprite itself is moving or if the sprite's changes in a way correlated with the mouse position (causing oscillation around the threshold), it could lead to the rapid flipping.
User
deat pixels doens't help because the second you go above the threshold it starts flipping like crazy
Assistant
If the sprite is still flipping rapidly, it's likely due to the fact that the check for changing the sprite's direction is happening every frame without maintaining a state for the last direction faced. If the mouse_position.x is near the sprite's position.x, and there's any fluctuation in relative positions, this could lead to rapid flipping.
A more robust approach would involve maintaining a state for the last direction the sprite faced and only changing that direction when there's a clear intent to face the other way. This state-based logic will prevent continuous flipping.
User
now it only change once as you move and you have to change direction to be able to look the other way after it has turned
Assistant
The issue you're describing suggests that the sprite's direction isn't updating as expected in response to subsequent changes in mouse position. A simple and effective way to resolve this would be to use boolean flags that only allow the sprite to flip under certain conditions.
Here is an update to the example code that includes a flag, can_flip, which determines if flipping is currently allowed. We will reset this flag when the mouse has moved enough in the opposite direction.
User
Invalid call. Nonexistent function 'instatiate' in base 'PackedScene'.
extends Node2D
var controller = null
var mana_cost = 10
Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
func execute(s):
controller = s
var is_able_to_cast = controller.can_cast_ability(mana_cost)
if !is_able_to_cast: return
var f = load("res://Scenes/abilities/swordslash/swordslash_wave.tscn")
var f_node = f.instatiate()
f_node.controller = controller
f_node.position = controller.global_position
f_node.add_collision_exception_with(controller)
get_node("/root").add_child(f_node)
Assistant
The error message you are seeing is due to a typo in your code. The correct function for creating an instance of a PackedScene in Godot is instance(), not instatiate().
Here's your code with the typo corrected:
extends Node2D
var controller = null
var mana_cost = 10
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
func execute(s):
controller = s
var is_able_to_cast = controller.can_cast_ability(mana_cost)
if !is_able_to_cast: return
# Load the scene resource
var f = load("res://Scenes/abilities/swordslash/swordslash_wave.tscn")
# Corrected here: instance() instead of instatiate()
var f_node = f.instance()
f_node.controller = controller
f_node.position = controller.global_position
f_node.add_collision_exception_with(controller)
get_node("/root").add_child(f_node)
User
Invalid call. Nonexistent function 'instatiate' in base 'PackedScene'.
extends Node2D
var controller = null
var mana_cost = 10
Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
func execute(s):
controller = s
var is_able_to_cast = controller.can_cast_ability(mana_cost)
if !is_able_to_cast: return
var f = load("res://Scenes/abilities/swordslash/swordslash_wave.tscn")
var f_node = f.instatiate()
f_node.controller = controller
f_node.position = controller.global_position
f_node.add_collision_exception_with(controller)
get_node("/root").add_child(f_node)
extends CharacterBody2D
@onready var aim_pos = null
@onready var self_pos = null
#Data
var speed : int = 320
var damage : int = 5
var controller = null
how can I change from where the ability gets cast from? wanna cast it from a thing called $Hand from the controller:
func execute(s):
controller = s
var is_able_to_cast = controller.can_cast_ability(mana_cost)
if !is_able_to_cast: return
var f = load("res://Scenes/abilities/swordslash/swordslash_wave.tscn")
var f_node = f.instantiate()
f_node.controller = controller
f_node.position = controller.global_position
f_node.add_collision_exception_with(controller)
get_node("/root").add_child(f_node)
Assistant
To cast the ability from a specific node attached to the controller, such as $Hand, you can change the position from the controller.global_position to the global position of the Hand node.
Here's how you might modify the execute function:
func execute(s):
controller = s
var is_able_to_cast = controller.can_cast_ability(mana_cost)
if not is_able_to_cast:
return
var f = load("res://Scenes/abilities/swordslash/swordslash_wave.tscn")
var f_node = f.instance()
f_node.controller = controller
# Change the starting position of the ability to the global position of the 'Hand' node
var hand_node = controller.get_node("Hand") # Adjust this if 'Hand' is more deeply nested
if not hand_node:
print("Error: Hand node not found in the controller.")
return
f_node.position = hand_node.global_position
f_node.add_collision_exception_with(controller)
get_tree().root.add_child(f_node)
User
apply the rotation of the direction to the sprite
Assistant
It looks like you're working with a script within the Godot Engine for handling player input and sprite direction based on mouse position. To ensure the sprite changes its direction when moving left (assuming < 0 refers to the x-direction of the direction vector), below is the corrected code with explanations:
func _read_input():
var mouse_position = get_global_mouse_position()
var direction = (mouse_position - position).normalized()
# If the sprite's direction.x is less than 0, flip it to face left
if direction.x < 0:
scale.x = -abs(scale.x) # Ensure the sprite faces left
else:
scale.x = abs(scale.x) # Ensure the sprite faces right
# Initialize an empty array to hold movement directions
var movement = []
# Check for input and append corresponding directions
if Input.is_action_pressed("move_up"): movement.append("up")
if Input.is_action_pressed("move_down"): movement.append("down")
if Input.is_action_pressed("move_right"): movement.append("right")
if Input.is_action_pressed("move_left"): movement.append("left")
# Call a function to execute the movement (make sure move has an 'execute' method)
move.execute(self, movement)
# Check for and handle ability-related inputs (interact, fireball, inventory)
if last_ability > global_cooldown:
if Input.is_action_just_pressed("interact"):
interact()
last_ability = 0
# The following lines are commented out, but if you wish to implement these abilities,
# you will need to uncomment them and ensure 'fireball' and 'inventory' have 'execute' methods
#if Input.is_action_just_pressed("ability_1"):
# fireball.execute(self)
# last_ability = 0
#if Input.is_action_just_pressed("inventory"):
# inventory.execute(self)
# last_ability = 0
Here's an explanation of what was changed:
When changing the sprite's direction (scale.x), we ensure that we only flip the x-scale but preserve its absolute value so that it always flips correctly without altering the sprite's size.
The abs() function ensures that the scale remains positive or negative depending on the direction, but doesn't become smaller or larger, which might happen if you just set it to -1 or 1 without considering its current scale.
Also, ensure that your move instance has a method named execute that takes in the movement array and acts upon it. Similarly, make sure there are interact(), fireball.execute(), and inventory.execute() methods if you plan to use those abilities.
The lines related to abilities are commented out. If you want to activate those abilities when certain inputs are received, you need to uncomment them and implement the appropriate logic for those actions.
_read_input()
position
direction.x < 0
To mitigate this, you should ensure that the flipping only happens at discrete points, rather than continuously as the mouse hovers around the threshold. One way to do this is to add a dead zone or hysteresis, where the direction is only reversed when the mouse position goes clearly past a certain point relative to the sprite.
Here is how you might implement such a solution:
var flip_threshold = 10 # pixels; adjust as needed for dead zone
func _read_input():
var mouse_position = get_global_mouse_position()
var direction = (mouse_position - position).normalized()
# Apply hysteresis to avoid rapid flipping when the mouse is near
# the left edge of the sprite
if direction.x < 0 and abs(mouse_position.x - position.x) > flip_threshold:
scale.x = -abs(scale.x) # Ensure the sprite faces left
elif direction.x > 0 and abs(mouse_position.x - position.x) > flip_threshold:
scale.x = abs(scale.x) # Ensure the sprite faces right
# ... rest of the code remains the same ...
The flip_threshold value creates a buffer zone around the direction.x < 0 check, which should prevent the rapid flipping unless the mouse moves a certain distance away from the threshold. If the sprite's position or some other element of the game's state is causing the mouse position check to become invalid, you'll need to adjust the logic accordingly or check why the position is oscillating so that you can prevent this behavior.
Here's an example of how you might implement this:
var facing_direction = 1 # 1 for right, -1 for left
func _read_input():
var mouse_position = get_global_mouse_position()
var direction = (mouse_position - position).normalized()
# Change the facing direction only if the mouse position is clearly on the other side
# of the sprite
if direction.x < 0 and facing_direction != -1:
scale.x = -abs(scale.x)
facing_direction = -1 # Update facing direction state
elif direction.x > 0 and facing_direction != 1:
scale.x = abs(scale.x)
facing_direction = 1 # Update facing direction state
# ... rest of the code remains the same ...
In this implementation, we've added a facing_direction variable that keeps track of which way the sprite is currently facing. With this approach, the sprite's scale will only change when the mouse has definitely passed to the other side (left or right) of the sprite and the facing direction will change accordingly. This should mitigate flipping unless the mouse passes to the opposite side of the sprite relative to its current facing direction.
If you're still experiencing issues, check if there are other parts of your code (outside the snippet you've shared) that might be conflicting with the directional logic here. Also, make sure that the position attribute is not being updated in a way that conflicts with the scale.x attribute, as this could cause rapid flipping if the sprite's position moves back and forth across the mouse position threshold.
# Script-level variable to remember if the sprite can flip
var can_flip = true
func _read_input():
var mouse_position = get_global_mouse_position()
var direction = (mouse_position - position)
# The flip is only allowed when can_flip is true and the direction has clearly changed
if can_flip:
if direction.x < 0:
scale.x = -abs(scale.x) # Sprite faces left
can_flip = false # Prevent further flipping until conditions are met
elif direction.x > 0:
scale.x = abs(scale.x) # Sprite faces right
can_flip = false # Prevent further flipping until conditions are met
# If the mouse is a sufficient distance away from the sprite's center in the x-direction,
# allow flipping again
if abs(direction.x) > flip_threshold:
can_flip = true
# ... rest of the code for movement and interaction ...
This code maintains a variable can_flip, which is only set back to true once the mouse has moved a certain distance away (flip_threshold) from the sprite's position.x. This approach ensures that once the sprite has flipped direction, it won't flip back immediately unless the mouse is moved sufficiently to the other side.
Adjust flip_threshold accordingly to create a comfortable dead zone where the direction will not flip.
If this solution still doesn't work for you, then there might be other interactions in your code that are causing unanticipated behavior, and further inspection and debugging would be needed to isolate the issue. Remember to consider all the places in your code where scale.x or position might be modified, as they could inadvertently interact with this flipping logic.
After making this correction, the f.instatiate() line will properly create an instance of the PackedScene and the rest of your code will execute without the error you were experiencing.
Remember to test that the controller object has a global_position attribute and a method add_collision_exception_with that can be called appropriately by f_node.
Also, make sure that the controller has the can_cast_ability(mana_cost) method and that it returns a boolean value to determine whether the ability can be cast. If either of these is not the case, you might need to fix or implement them accordingly for your script to function as intended.
func _physics_process(delta):
move_and_slide()
var collision = get_last_slide_collision()
if(collision && collision.get_collider()):
var collider = collision.get_collider()
if collider.get_groups().size() && collider.get_groups().has("entity"):
var enemy_group = controller.get_enemy_group()
if collider.get_groupds().size() && collider.get_groups().has(enemy_group):
collider.apply_damage(damage)
print(collider.current_health)
_explode()
The error is still due to the same typo in your code. In the execute function, you need to correct the typo from instatiate to instance. Let's fix that first:
func execute(s):
controller = s
var is_able_to_cast = controller.can_cast_ability(mana_cost)
if !is_able_to_cast: return
var f = load("res://Scenes/abilities/swordslash/swordslash_wave.tscn")
var f_node = f.instance() # Corrected the typo here
f_node.controller = controller
f_node.position = controller.global_position
f_node.add_collision_exception_with(controller)
get_node("/root").add_child(f_node)
Now, let's look at the second script. It appears to be the script for the swordslash_wave scene. I see a couple of problems that we should address:
aim_pos and self_pos are set to null at the beginning of the script but are reassigned in the _ready function. Make sure that these positions are correctly obtained from the controller.
When defining onready variables, you can't use null for initialization. Instead, do it within the _ready function.
Here is the corrected code for the second script:
extends CharacterBody2D
# No need to initialize onready variables to null
@onready var aim_pos
@onready var self_pos
#Data
var speed : int = 320
var damage : int = 5
var controller
func _ready():
self_pos = self.global_position
# Make sure you call get_aim_position() if it's a method
aim_pos = controller.get_aim_position()
velocity = self_pos.direction_to(aim_pos) * speed
# Start a timer for the explosion
var timer = get_tree().create_timer(2)
yield(timer, "timeout")
_explode()
func _explode():
self.queue_free()
func _physics_process(delta):
move_and_slide(velocity)
# Check for collisions
for i in range(get_slide_count()):
var collision = get_slide_collision(i)
if collision != null:
var collider = collision.collider
if collider and collider.is_in_group("entity"):
var enemy_group = controller.get_enemy_group()
if collider.is_in_group(enemy_group):
collider.apply_damage(damage)
print(collider.current_health)
_explode()
break
Notable changes or fixes:
Changed the way aim_pos is set to call the method get_aim_position(). Make sure get_aim_position is a valid method in the controller.
Replaced the previous way to get collisions with a loop that goes through all slide collisions (to handle multiple collisions).
Added a check to see if the collider is non-null and is in the "entity" group before further interaction.
Please review these changes and adjust according to your actual game logic and object hierarchy. This should get rid of the error you have encountered and clean up the collision logic in the swordslash_wave script. Make sure to verify that the methods get_aim_position and get_enemy_group exist in the controller script and are accessible from these instances.
Make sure to provide the correct path to the Hand node. If the Hand node is located directly under controller, the get_node("Hand") path is sufficient. However, if the Hand node is nested more deeply, you will need to adjust the path accordingly.
In addition, ensure that the Hand node exists and is part of the controller's scene tree at the time this script attempts to access it. If the Hand node is dynamically added or removed, you may need to include checks to ensure that it is present before trying to use its position.
To apply the rotation of the direction to a sprite, you first need to calculate the directional vector from the sprite to the target (or from one point to another). After you've obtained this directional vector, you can calculate the necessary rotation and apply it to your sprite's rotation.
Assuming you already have your directional vector calculated (which represents the direction you want your sprite to face), here's how you can do it in Godot:
# Calculate the direction vector
var direction = target_position - sprite_position
# Calculate the angle to rotate
var angle = atan2(direction.y, direction.x)
# Rotate the sprite to face the target
sprite.rotation = angle
If you want to set the rotation of the sprite while casting an ability and have the ability's direction also apply to the sprite that casts it, you can expand your execute function from earlier:
func execute(s):
controller = s
var is_able_to_cast = controller.can_cast_ability(mana_cost)
if not is_able_to_cast:
return
var f = load("res://Scenes/abilities/swordslash/swordslash_wave.tscn")
var f_node = f.instance()
f_node.controller = controller
# Assume hand_node is relative to controller
var hand_node = controller.get_node("Hand")
if not hand_node:
print("Error: Hand node not found in the controller.")
return
# Set position of the ability to the global position of the 'Hand' node
f_node.position = hand_node.global_position
# If you want the ability to be rotated to face the controller's aim direction:
if controller.has_method("get_aim_direction"):
var aim_direction = controller.get_aim_direction() # This method should return a Vector2
f_node.rotation = atan2(aim_direction.y, aim_direction.x)
else:
print("The controller does not have a method get_aim_direction.")
# Add collision exception and add ability to the tree
f_node.add_collision_exception_with(controller)
get_tree().root.add_child(f_node)
In the above code snippet, get_aim_direction is a hypothetical method on your controller. This method should return a Vector2 representing the aim direction which you would get from your controls, for example, the direction from the player to the mouse cursor. If the direction you want to use is not from a method like get_aim_direction, you'd need to calculate it in another way befitting your game.
Make sure the has_method call matches the actual method name you've implemented, and ensure that the Hand node exists on the controller. If the Hand or aiming is more complicated, such as being jointed or animated, you'll need to account for those details in your code.