Random Shaking using Tween in Godot
By Hideki Ishiguro at
If you want to create shaking movements, basically you can make do it by setting set_offset in the process(delta) as mentioned in the Godot FAQ.
But it's difficult to customize for more tricky movements. We can do it if we want to, but it's definitely a hassle.
For that reason, I will use Tween instead of that.
Tween is an even more customizable node than AnimationPlayer, so it is useful for expressing random movements in script.
This article explains how to shake randomly a Node object such as Sprite.
1. Sprite and Tween
First, create Sprite node and add Tween node in it.
Assign the Godot icon to the texture of Sprite.
Next, connect the signal of Tween named tween_completed.
2. Create a script
After that, assign the script to the Sprite and write code as follows:
extends Sprite
var shake_amount = 5.0
var shake_speed = 0.1
var current_pos = Vector2()
var final_pos = Vector2()
var rng = RandomNumberGenerator.new()
func _ready():
rng.randomize()
shake()
func shake():
current_pos = position
final_pos = Vector2(
rng.randf_range(-1.0, 1.0),
rng.randf_range(-1.0, 1.0)) * shake_amount
$Tween.interpolate_property(
self,
"position",
current_pos,
final_pos,
shake_speed,
Tween.TRANS_LINEAR,
Tween.EASE_IN_OUT
)
$Tween.start()
func _on_Tween_tween_completed(object, key):
shake()
3. Shake it!
Click Run. You should see that the sprite is shaking as below.
If you want it to shake faster and stronger, change values of the shake_amount and shake_speed.
var shake_amount = 20.0
var shake_speed = 0.01
Then, Sprite will shake violently.