How can I create a clone that follows my player's input but with a 1 second delay?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By abdallhhelles

I want to make a clone follow my player’s exact movements using the player’s input.

:bust_in_silhouette: Reply From: estebanmolca

Hi…i leave you a very basic example using yield:

extends Node2D
var sprite
var shadow 

func _ready():
	sprite = $Sprite
	shadow =$Sprite.duplicate()
func _physics_process(delta):
	if Input.is_action_pressed("ui_right"):
		$Sprite.position.x += 1
		yield(get_tree().create_timer(1), "timeout")
		shadow.position.x += 1
	elif Input.is_action_pressed("ui_left"):
		$Sprite.position.x -= 1
		yield(get_tree().create_timer(1), "timeout")
		shadow.position.x -= 1	

What if I want the Shadow to move using the input as well?
and the delay doesn’t seem to work.

abdallhhelles | 2021-08-17 19:51

It is a very basic example and it works, I already tried it. It is a Node2D with a child Sprite. The shadow moves with the same input, only the yield function delays it 1 second. In this case, duplicate the Sprite with duplicate but it could be another sprite or node. Since I don’t know what your configuration is, I put this example to give you an idea. If you want more details please post your scene.

estebanmolca | 2021-08-18 04:12

It’s working perfectly … thanks you!

but what I meant is how can I make the shadow move with input.
not with shadow.position.x
should I add movement and physics variables in the shadow script? (I have the shadow already created as a child)

abdallhhelles | 2021-08-18 12:36

Any link to a video, image that shows more or less what you want to achieve?

estebanmolca | 2021-08-20 15:24

Like in the game Celeste, when Madeline is being chased by Badeline

abdallhhelles | 2021-08-20 18:34

Well, I don’t know if I saw the correct part of the video but what you want to achieve is nothing trivial. One way would be by registering the inputs and the positions where you execute them in an array. Then the shadow reads that array and executes the movements with the desired time delay. For that the characters have to be, how to say, generalized, abstracted. The characters move because they receive a command to move. Then later in a general input function, you generate the commands, register them and send them to the characters, in this case they would also have to receive the position where the command was executed and/or by time.
There is a pattern called Command:
Command · Design Patterns Revisited · Game Programming Patterns

and pattern State:

This is all I can tell you based on what I saw in the video (The character chased by various shadows). Ask me if you want details about something specific or you can ask again in the forum to see if there is someone who can give you another answer.

estebanmolca | 2021-08-20 19:36