How to write character's position to a file?

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

I have character that moves with keyboard inputs and I need to know how to record the movement and write it to a file. I use the ‘func _process(delta)’ function so I would like to record the character’s translation and rotation from each frame. I don’t know if this is helpful, but this is how I have the movement coded:

extends RigidBody

func _process(delta):
if(Input.is_key_pressed(KEY_LEFT)):
translate_object_local((Vector3(0,0,delta7)))
if(Input.is_key_pressed(KEY_RIGHT)):
translate_object_local((Vector3(0,0,-delta
7)))

For better readability (and maybe solve the problem quicker), may I suggest formatting the GDscript with spaces. For each of the code snippets, indent them four spaces.

Anyway, you may be able to do that via the mechanism called serialization. You can save the lines in a file like this:

var file = File.new()
file.open("user://movement.txt", File.WRITE)
file.store_line(character_position)
file.close()

With this code, you could probably save the character’s position to a file. Having written that, it may not be a great idea to constantly write the character’s position to a file, as that could waste CPU cycles.

Ertain | 2019-07-23 23:23

:bust_in_silhouette: Reply From: Xian

Here

func process(delta):
   	var file = File.new()
    	if (file.open("user://movement.txt", File.READ_WRITE) == OK):
			file.seek_end()
			file.store_line("\r")
   			file.store_line(str(self.translation)+"\n"+str(self.rotation)+"\n")
    		file.close()
    	else:
    		print("Error writing file")