Writing and reading position data

Hello, I am trying to create a tool that records player position data into a .txt file that can later be read by another object to replay the players movement. In my current implementation of this I can record the data to a .txt file but I’m unsure as how I could load that data so that another object independent of the player could replay the players movement. (I.e. think time trial ghosts, or doom demo files.) I am still new to game development, so please, if there is something I should be doing differently please let me know. Thanks!

Current Implementation:

@export var playback_object = Node2D

var frames = 0
var reccording_data = {}

func _process(delta):
	if Input.is_action_just_pressed("extra"):
		$delay_timer.stop()
	if Input.is_action_just_pressed("up"):
		save_reccording()

func record():
	reccording_data[frames] = {}
	var cur_obj = recorded_object
	reccording_data[frames][cur_obj] = {"position" : cur_obj.global_position.round() + Vector2(0, -15)}
	frames += 1
	
	$delay_timer.start()

func save_reccording():
	var file = FileAccess.open("res://data.txt", FileAccess.WRITE)
	if file:
		file.store_var(reccording_data)
		file.close()
	else:
		print("error")

func _on_delay_timer_timeout():
	record()

Recording position alone won’t be enough for proper “replay” as you don’t know when the object was at that position. You at least need to record the timestamp as well.

I record the position and the frame it occurs at. It can replay, I just don’t know how to read this data and use it in another scene from the .txt file

Well, use FileAccess and get_var() to get the same dictionary you’ve stored.

Storing a frame is not the best option because frame rate may vary. Better to store the real time i.e. the accumulated delta.

Would suggest working with Custom Resource.
You can easily Resource load and save that way.

Note: To access project resources once exported, it is recommended to use ResourceLoader instead of FileAccess, as some files are converted to engine-specific formats and their original source files might not be present in the exported PCK package. If using FileAccess, make sure the file is included in the export by changing its import mode to Keep File (exported as is) in the Import dock, or, for files where this option is not available, change the non-resource export filter in the Export dialog to include the file’s extension (e.g. *.txt).

1 Like

Definitely use a Resource. You don’t even need to go through ResourceLoader for this. Simply use load()

1 Like