I'm trying to program a textbox that I can write in using the keyboard; but the backspace key doesn't erase text, nothing happens when I press it.
extends Node2D
onready var Text = $Panel/RichTextLabel
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
func _unhandled_input(event):
if event is InputEventKey:
if event.pressed == true:
match event.scancode:
KEY_A:
Text.append_bbcode("a")
KEY_BACKSPACE:
if Text.get_total_character_count() > 0:
print("0")
Text.visible_characters -= 1
pass
Godot already has a built-in TextEdit node that does exactly what you are trying to do.
I'm trying to animate an expandable staff by travel between nodes in AnimationTree Like this:
...
tool
export(String,"small", "mid", "full") var staff_mode = "small" setget set_staff_mode;
func set_staff_mode(new_val):
var ani_state;
if(self.has_node("/path/to/AnimationTree")):
ani_state=self.get_node("/path/to/AnimationTree")["parameters/playback"];
ani_state.start(staff_mode);
print(ani_state.is_playing());
ani_state.travel(new_val);
ani_state.stop();
staff_mode=new_val;
I haven't applied autoplay to small because I don't want a looping animation on the staff
(it only expands or compresses, no idle animation)
but for some reason it gives the error:
Can't travel to 'full' if state machine is not playing. Maybe you
need to enable Autoplay on Load for one of the nodes in your state
machine or call .start() first?
Edit:
I forgot to mention but I don't have any idle animation for my staff so I need to stop the animation after the transition is complete.
small, mid & full
(all of them are static modes of the staff depending upon the game how much the staff should extend)
are all 0.1sec single frame animations and I applied Xfade Time of 0.2 secs to show the transition
I simply need to transition from an existing animation state to another and then stop
New Answer
Apparently the solution on the old answer does not work for very short animations. And the workarounds begin to seem to much overhead for my taste. So, as alternative, let us get rid of the AnimationTree and work directly with AnimationPlayer. To do this, we will:
Increase the animation duration to be long enough for the "cross fade" time (e.g. 0.2 seconds).
Put the "cross fade" time in "Cross-Animation Blend Times". For each animation, select it on the Animation panel and then select "Edit Transition…" from the animation menu, that opens the "Cross-Animation Blend Times" where you can specify the transition time to the other animations (e.g. 0 to itself, 0.1 to "adjacent" animation, and so on).
Now we can simply ask the AnimationPlayer to play, something like this:
tool
extends Node2D
enum Modes {full, mid, small}
export(Modes) var staff_mode setget set_staff_mode
func set_staff_mode(new_val:int) -> void:
if staff_mode == new_val:
return
if not is_inside_tree():
return
var animation_player := get_node("AnimationPlayer") as AnimationPlayer
if not is_instance_valid(animation_player):
return
var target_animation:String = Modes.keys()[new_val]
animation_player.play(target_animation)
yield(animation_player, "animation_finished")
staff_mode = new_val
property_list_changed_notify()
I have opted to use an enum, because this will also allow me to "travel" between the animations. The idea is that we will make a for loop where we call the animations in order. Like this:
tool
extends Node2D
enum Modes {full, mid, small}
export(Modes) var staff_mode:int setget set_staff_mode
func set_staff_mode(new_val:int) -> void:
if staff_mode == new_val:
return
if not is_inside_tree():
return
var animation_player := get_node("AnimationPlayer") as AnimationPlayer
if not is_instance_valid(animation_player):
return
var old_val := staff_mode
staff_mode = new_val
var travel_direction = sign(new_val - old_val)
for mode in range(old_val, new_val + travel_direction, travel_direction):
var target_animation:String = Modes.keys()[mode]
animation_player.play(target_animation)
yield(animation_player, "animation_finished")
I have also decided to set staff_mode early so I can avoid property_list_changed_notify.
Concurrent calls may result in animation stopping early, since calling play stops the currently playing animation to play the new one. However, I don't think waiting for the current animation to end is correct. Also with so short animations, it should not be a problem.
Version using Tween
Using Tween will give you finer control, but it is also more work, because we are going to encode the animations in code… Which I will be doing with interpolate_property. Thankfully this is a fairly simple animation, so can manage without making the code too long.
Of course, you need to add a Tween node. We will not use AnimationPlayer nor AnimationTree. Tween will handle the interpolations (and you can even specify how to do the interpolations by adding the optional parameters of interpolate_property, which I'm not passing here).
This is the code:
tool
extends Node2D
enum Modes {full, mid, small}
export(Modes) var staff_mode:int setget set_staff_mode
func set_staff_mode(new_val:int) -> void:
if staff_mode == new_val:
return
if not is_inside_tree():
return
var tween := get_node("Tween") as Tween
if not is_instance_valid(tween):
return
var old_val := staff_mode
staff_mode = new_val
var travel_direction = sign(new_val - old_val)
for mode in range(old_val, new_val + travel_direction, travel_direction):
match mode:
Modes.full:
tween.interpolate_property($"1", "position", $"1".position, Vector2.ZERO, 0.2)
tween.interpolate_property($"1/2", "position", $"1/2".position, Vector2(0, -35), 0.2)
tween.interpolate_property($"1/2/3", "position", $"1/2/3".position, Vector2(0, -34), 0.2)
Modes.mid:
tween.interpolate_property($"1", "position", $"1".position, Vector2.ZERO, 0.2)
tween.interpolate_property($"1/2", "position", $"1/2".position, Vector2(0, -35), 0.2)
tween.interpolate_property($"1/2/3", "position", $"1/2/3".position, Vector2.ZERO, 0.2)
Modes.small:
tween.interpolate_property($"1", "position", $"1".position, Vector2.ZERO, 0.2)
tween.interpolate_property($"1/2", "position", $"1/2".position, Vector2.ZERO, 0.2)
tween.interpolate_property($"1/2/3", "position", $"1/2/3".position, Vector2.ZERO, 0.2)
tween.start()
yield(tween, "tween_all_completed")
What you can see here is that I have encoded the values from the tracks of from the AnimationPlayer in the source code. Using Tween I get to tell it to interpolate from whatever value the track has to the target position of each state.
I don't know if this performs better or worse compared to AnimationPlayer.
Old Answer
Alright, there are two sides to this problem:
travel is supposed to play the animation, so it is not instantaneous. Thus, if you call stop it will not be able to travel, and you get the error message you got.
Ah, but you cannot call start and travel back to back either. You need to wait the animation to start.
I'll start by not going from one state to the same:
func set_staff_mode(new_val:String) -> void:
if staff_mode == new_val:
return
We are going to need to get the AnimationTree, so we need to ge in the scene tree. Here I use yield so the method returns, and Godot resumes the execute after it gets the "tree_entered" signal:
if not is_inside_tree():
yield(self, "tree_entered")
The drawback of yield, is that it can cause an error if the Node is free before you get the signal. Thus, if you prefer to not use yield, we can do this instead:
if not is_inside_tree():
# warning-ignore:return_value_discarded
connect("tree_entered", self, "set_staff_mode", [new_val], CONNECT_ONESHOT)
return
Here CONNECT_ONESHOT ensures this signal is automatically disconnected. Also, Godot makes sure to disconnect any signals when freeing a Node so this does not have the same issue as yield. However, unlike yield it will not start in the middle of the method, instead it will call the method again.
Alright, we get the AnimationTree:
var animation_tree := get_node("/path/to/AnimationTree")
if not is_instance_valid(animation_tree):
return
And get the AnimationNodeStateMachinePlayback:
var ani_state:AnimationNodeStateMachinePlayback = animation_tree.get("parameters/playback")
Now, if it is not playing, we need to make it playing:
if not ani_state.is_playing():
ani_state.start(new_val)
And now the problem: we need to wait for the animation to start.
In lieu of a better solution, we going to pool for it:
while not ani_state.is_playing():
yield(get_tree(), "idle_frame")
Previously I was suggesting to get the AnimationPlayer so we can wait for "animation_started", but that does not work.
Finally, now that we know it is playing, we can use travel, and update the state:
ani_state.travel(new_val)
staff_mode = new_val
Don't call stop.
You might also want to call property_list_changed_notify() at the end, so Godot reads the new value of staff_mode, which it might not have registered because we didn't change it right away (instead we yielded before changing it). I suppose you could alternatively change the value earlier, before any yield.
By the way, if you want the mid animation to complete in the travel, change the connections going out of mid in the AnimationTree from "Immidiate" to "AtEnd".
Addendum on waiting for travel to end and stop
We can spin wait in a similar fashion as we did to wait for the AnimationNodeStateMachinePlayback to start playing. This time we need to pool two things:
What is the current state of the animation.
What is the playback position on that animation.
As long as the animation is not in the final state and as long as it has not reached the end of that animation, we let one frame pass and check again. Like this:
while (
ani_state.get_current_node() != new_val
or ani_state.get_current_play_position() < ani_state.get_current_length()
):
yield(get_tree(), "idle_frame")
Then you can call stop.
Furthermore, I'll add a check for is_playing. The reason is that this code is waiting for the AnimationTree to complete the state we told it to… But if you call travel again before it finished, it will go to new destination, and thus might never reach the state we expected, which result in spin waiting for ever.
And since it might not have arrived to the state we expected, I decided to query the final state instead of setting staff_mode to new_val. That part of the code now looks like this:
ani_state.travel(new_val)
while (
ani_state.is_playing() and (
ani_state.get_current_node() != new_val
or ani_state.get_current_play_position()
< ani_state.get_current_length()
)
):
yield(get_tree(), "idle_frame")
ani_state.stop()
staff_mode = ani_state.get_current_node()
property_list_changed_notify()
I have aQt PySide6 app with a centralWidget taken by a Vispy Canvas (OpenGL).
I try to pilot parameters azimuth and elevation of the camera showing the 3D OpenGL environment shown in central widget of the main window.
I have two QSliders in a DockWidget (range -1.0, 1.0, default value 0.0). I try to connect their isPressed() to a method in which I first move the camera by delta increment based on myslider.value(), then test if myslider.isSliderDown() is True, and if so recursively calls the same method. Else (slider released) it sets back the slider at its origin: my slider.setValue(0).
I so would like to have a kind of joystick behaviour. Wen pressed and dragged, the camera rotates/moves, more or less rapidly following the displacement of the slider, and then stops when slider is released, this one jumping back to center position/value.
All I have with this implementation is an infinite loop as soon as I press and drag the slider. Releasing it does not stop the loop.
Why mySlider.isSliderDown() does not reflect the status of the slider? Am I, because of the recursive call, blocked inside the first slot connection call, never going out to reevaluate GUI state?
If so, how should I code this?
Here is a solution with QTimer:
...
self.cameraModTimer = QTimer(self)
self.cameraModTimer.timeout.connect(self.updateCamera)
self.fovSlider = CameraParamSlider(Qt.Vertical, self, fovLabel, "fov", 1.0e3)
self.fovSlider.sliderPressed.connect(self.startCameraUpdate)
self.fovSlider.sliderReleased.connect(self.stopCameraUpdate)
...
with
#Slot()
def updateCamera(self):
if self.fovSlider.isSliderDown() is True:
self.fovSlider.updateParam()
#Slot()
def startCameraUpdate(self):
"""
Start the QTimer that will trigger updateParam as long as it's not stopped
"""
self.cameraModTimer.start()
#Slot()
def stopCameraUpdate(self):
"""
Stop the QTimer that triggered updateParam. This also sets back the sliders
to their default position and calls a last time updateParam to refresh
sliders labels after having been reset.
"""
self.cameraModTimer.stop()
self.fovSlider.setValue(0.0)
self.fovSlider.updateParam()
I'm following a tutorial series by Heartbeast.
My grass area2D is being collided with TileMap:1373 in the beginning
extends Node2D
func create_grass_effect():
var GrassEffect = load("res://Effects/GrassEffect.tscn")
var grassEffect = GrassEffect.instance()
var world = get_tree().current_scene
world.add_child(grassEffect)
grassEffect.global_position = global_position
func _on_Hurtbox_area_entered(area):
pass
func _on_Hurtbox_body_shape_entered(body_id, body, body_shape, local_shape):
print(body_id, body, body_shape, local_shape)
func _on_Hurtbox_body_shape_entered(body_id, body, body_shape, local_shape):
print(body_id, body, body_shape, local_shape)
console
1373[TileMap:1373]100
1373[TileMap:1373]100
1373[TileMap:1373]110
Despite moving all tile maps out of the way for the two small green grasses:
When I tell the script to queue_free() on _on_Hurtbox_area_entered:
Flipping the code doesn't work because when I have this code:
extends Node2D
func create_grass_effect():
var GrassEffect = load("res://Effects/GrassEffect.tscn")
var grassEffect = GrassEffect.instance()
var world = get_tree().current_scene
grassEffect.global_position = global_position
world.add_child(grassEffect)
func _on_Hurtbox_area_entered(area):
queue_free()
func _on_Hurtbox_body_shape_entered(body_id, body, body_shape, local_shape):
print(body_id, body, body_shape, local_shape)
The grass disapears anyways.
So the problem must be due to the signal or queue_free()
EDITTTTT:
I was looking and I think this solved my problem:
The question isn't entirely clear on what you want to trigger the signal, but I assume you want it to fire when the player enters the area. The docs for area_entered say:
Emitted when another area enters.
The player is a PhysicsBody, not an Area. Use body_entered instead:
Emitted when a physics body enters.
The body argument can either be a PhysicsBody2D or a TileMap instance (while TileMaps are not physics body themselves, they register their tiles with collision shapes as a virtual physics body).
So I guess the signal is wrong then...
The grass is touching itself and causing it self to queue_free()
I solved the problem by putting the grasses apart from each other.
Despite using a QThread, the GUI is still freezing
(code posted at end)
The space bar is hit which starts playing midi notes by creating the thread and emitting calls to the play function
if self.playing is False:
# PlayThread is initiated in PianoRoll when the space bar is hit.
Loop iterates and plays data, freezing the GUI
else:
# This section is not reached because another space bar hit cannot be received while data is looping
I have viewed the following tutorials and a variety of responses on StackOverflow:
https://manojbits.wordpress.com/2013/01/24/threading-in-pyqt4/
the joplaete tutorial
I've tried the following:
placing all looping code to run in the signaled function
placing the loop in the thread's run function and passing the data to the signaled function with emit
separating the function from the widget that handling the calls to it
making the data structures global (trying anything)
Please let me know what I am missing or if any other code is needed.
I am using an open source MIDI sequencer template
https://github.com/rhetr/seq-gui
class PlayThread(QtCore.QThread):
def __init__(self):
# qtcore.QThread.__init__(self, parent=app)
super(PlayThread , self).__init__()
self.signal = QtCore.SIGNAL("signal")
def run(self):
global xLocToNoteItems
# this loop was attempted in the signaled function as well
for xloc in xLocToNoteItems:
self.emit(self.signal, xloc)
# self.emit(self.signal, "arbitrary?")
# self.emit(QtCore.SIGNAL('update(QString)') + str(i))
in piano roll:
if event.key() == QtCore.Qt.Key_Space:
if self.playing:
self.playing = False
# terminate play thread
main.playThread.quit()
else:
self.playing = True
# playThread previously attempted to be stored in this (piano roll) class
# ...was moved to main in case the call was freezing the piano roll
main.playThread = PlayThread()
main.connect(main.playThread, main.playThread.signal, main.play)
main.playThread.start()
the play function was in the piano roll widget, now in main
def play(self, xloc):
# for xloc in main.xLocToNoteItems:
global xLocToRhythms
global xLocToNoteItems
for noteItem in xLocToNoteItems[xloc]:
player.note_on(noteItem.note[0], noteItem.note[3], 1)
offtime = xLocToRhythms[xloc]
time.sleep(offtime)
for noteItem in xLocToNoteItems[xloc]:
player.note_off(noteItem.note[0], noteItem.note[3], 1)
Your thread is deliberately emitting more than one signal to execute the play() method in the main thread. Your play method must be running for a reasonable amount of time and blocking the main thread (it for instance has a time.sleep in it).
You probably need to move the play code into the thread as well, but only if the MIDI library you are using is safe to call from a secondary thread. Note that you should also check if the library is thread safe if you plan to call the library from multiple threads.