实现用鼠标单击视口,图标移动到当前点击位置,并将位置信息封装为字典,然后转化为JSON格式,保存到外部文件,然后二次运行的时候,从外部文件读取JSON内容,转化为字典,然后再次还原上次的图标位置。

    这只是一个非常简单的案例,但是已经接触了Godot文件存取信息的核心。
    image.png

    1. extends Node2D
    2. var fPath = "res://txt.json"
    3. var json = {}
    4. func _ready():
    5. var f = File.new()
    6. # 文件是否存在
    7. if f.file_exists(fPath):
    8. f.open(fPath,File.READ)
    9. var text = f.get_as_text()
    10. f.close()
    11. # 将JSON文本转化为Godot字典。
    12. json = parse_json(text)
    13. print(json is Dictionary) # 返回true
    14. $icon.position.x = json.position.x
    15. $icon.position.y = json.position.y
    16. else: # 文件不存在
    17. json ={
    18. "position":{
    19. "x":$icon.position.x,
    20. "y":$icon.position.y,
    21. }
    22. }
    23. f.open(fPath,File.WRITE)
    24. f.store_string(to_json(json))
    25. f.close()
    26. func _input(event):
    27. # 鼠标点击
    28. if event as InputEventMouseButton:
    29. $icon.position = event.position
    30. json.position.x = $icon.position.x
    31. json.position.y = $icon.position.y
    32. # 将对象转化为JSON
    33. var text = to_json(json)
    34. var f = File.new()
    35. f.open("res://txt.json",File.WRITE)
    36. f.store_string(text)
    37. f.close()