How to change the speed of only a single node? - godot

I have a enemy KinematicBody2D and I want to slow down both it's movement & animation
I tried Engine.time_scale but it slows down the entire game,
so is there a way to slow down only a single node without effecting the others ?

There is no API to do that.
For your KinematicBody2D you could do something like this:
export var speed_factor := 1.0
func _process(delta:float) -> void:
delta *= speed_factor
#...
func _physics_process(delta:float) -> void:
delta *= speed_factor
#...
And for your AnimationPlayer you can set playback_speed (which you can also specify when you call play).
Alternatively you can set playback_process_mode to ANIMATION_PROCESS_MANUAL and then call advance and seek (in _process, for example) to make it advance.

Related

Godot how do i erase characters using backspace

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.

How to start & travel in AnimationTree using code?

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()

Godot Invalid to get index 'x' (On Base: 'Node (a.gd)')

im trying to hold a path to a game object (bat.tscn) in a script and use it to instanceate a object from a different script. Name of the script that holds the variable is called a.gd and the one that is responsible for instantiating is b.gd and the name of the variable is x. But for some reason every time i try to use the variable it gives me an error;
Invalid to get index 'x' (On Base: 'Node (a.gd)')
a.gd;
func _process(delta):
var SlotOne = $"res://Objects/Weapons/Bat.tscn
b.gd;
onready var InvManager = get_node("../a") #gets the script.
func _physics_process(delta):
changeWeapons()
func changeWeapons():
if Input.is_key_pressed(KEY_1):
load(InvManager.SlotOne)
elif Input.is_key_pressed(KEY_2):
print("2")
elif Input.is_key_pressed(KEY_3):
print("3")
elif Input.is_key_pressed(KEY_4):
print("4")
any ideas how can i fix this issue?
Im pretty new to the game engine so im kinda stuck here.
It appears you declared SlotOne inside of _process. That makes it a local variable. In other words, this variable will only be availabe inside that _process, and thus, you cannot reach it from another script.
Define the variables you want to reach from other scripts outside of any method (func) - the language guidlines encourage to place them near the start of the file, before any methods.
also a possible explanation is that instead of using or instancing the node you are trying to access it
so first try to add the node to the main scene like this
get_tree().current_scene().add_child("#the path to a.gd")
but anyways only the code can can tell us what is wrong
Well so it looks like you are just loading the scene instead of instancing it
this might help
first make sure that a.gd is a autoload script
then instead of writing the a.gd like this
func _process(delta):
var SlotOne = $"res://Objects/Weapons/Bat.tscn
write it like this
extends node
const SlotOne= preload("res://Objects/Weapons/Bat.tscn")
then write this on b.gd
func _physics_process(delta):
changeWeapons()
func changeWeapons():
if Input.is_key_pressed(KEY_1):
var Bat_instance = A.SlotOne.instance()
Bat_instance.position = Vector_2() #some position
self.add_child(Bat_instance)
elif Input.is_key_pressed(KEY_2):
print("2")
elif Input.is_key_pressed(KEY_3):
print("3")
elif Input.is_key_pressed(KEY_4):
print("4")

What is TileMap:1373

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.

VTK: how can I add a scrollbar to my project?

What's the easiest way to add a scrollbar to my VTK project ?
thanks
Update
def vtkSliderCallback2(obj, event):
sliderRepres = obj.GetRepresentation()
pos = sliderRepres.GetValue()
contourFilter.SetValue(0, pos)
SliderRepres = vtk.vtkSliderRepresentation2D()
min = 0 #ImageViewer.GetSliceMin()
max = 256 #ImageViewer.GetSliceMax()
SliderRepres.SetMinimumValue(min)
SliderRepres.SetMaximumValue(max)
SliderRepres.SetValue((min + max) / 2)
SliderRepres.SetTitleText("Slice")
SliderRepres.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
SliderRepres.GetPoint1Coordinate().SetValue(0.2, 0.6)
SliderRepres.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
SliderRepres.GetPoint2Coordinate().SetValue(0.4, 0.6)
SliderRepres.SetSliderLength(0.02)
SliderRepres.SetSliderWidth(0.03)
SliderRepres.SetEndCapLength(0.01)
SliderRepres.SetEndCapWidth(0.03)
SliderRepres.SetTubeWidth(0.005)
SliderRepres.SetLabelFormat("%3.0lf")
SliderRepres.SetTitleHeight(0.02)
SliderRepres.SetLabelHeight(0.02)
SliderWidget = vtk.vtkSliderWidget()
SliderWidget.SetInteractor(iren)
SliderWidget.SetRepresentation(SliderRepres)
SliderWidget.KeyPressActivationOff()
SliderWidget.SetAnimationModeToAnimate()
SliderWidget.SetEnabled(True)
SliderWidget.AddObserver("InteractionEvent", vtkSliderCallback2)
Just to be complete and for other users googling thing.
vtkSliderWidget will do what you want if you need it to set a value.
//edit based on your edit
If you want to get the value, you have to connect an event to the slider which is fired when the value is changed. Than retrieve this value and update accordingly. An example in C++ is found here
// I actually think my issue is that the callback function is invoked for each thumb position when I slide it. How can avoid that ? In other words I only want the last position to trigger the callback function...
Try coupling it to the EndInteractionEvent instead of to the InteractionEvent.
SliderWidget.AddObserver("EndInteractionEvent", vtkSliderCallback2)
// stuff
By the way, if you use python and VTK and need GUI stuff, I advice you to use the python QT and python qt widgets which ease up alot of this stuff. Some code of one of my old projects using QT+Python+VTK for GUI + python stuff:
self.verticalSlider = QtGui.QSlider(self.centralwidget)
self.verticalSlider.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider.setObjectName("verticalSlider")
self.horizontalLayout.addWidget(self.verticalSlider)
// connect slider to a method onValueChange
QObject.connect(self.verticalSlider, SIGNAL("valueChanged(int)"),
self.setFibreVolumeOpacity)
def setFibreVolumeOpacity(self, value):
// do stuff here with slider value.

Resources