Godot Version
4.2.2
Question
I am having trouble loading the 2d player position.
I can run the game and move the player around, but when i click F9 to update the player location to a value i pulled from a save file, I get terminal output like the player is not loaded.
What am i doing wrong?
Details:
The F9 key press runs this code in Player.gd:
elif Input.is_action_just_released("Load"):
print("loading from Input.is_action_just_released(Load)")
$"/root/World".load_game()
print("load attempt complete from Input.is_action_just_released(Load)")
Here is the related world.gd code with that $“/root/World”.load_game() function :
extends Node
const Global = preload("res://Global.gd")
const myplayer = preload("res://Player.gd")
@onready var sprite_2d: Sprite2D = $Player/Sprite2D
@onready var player : CharacterBody2D = $Player
func load_game():
print("starting load_game")
if not (player):
print("there is no player in world load_game")
else:
print("in world load_game player.global_position is > "+str(player.global_position))
if not FileAccess.file_exists("user://samegame.save"):
print("failed to load user://samegame.save")
return
var save_game = FileAccess.open("user://samegame.save", FileAccess.READ)
while save_game.get_position() < save_game.get_length():
var json_string = save_game.get_line()
var json = JSON.new()
var parse_result = json.parse(json_string)
var node_data = json.get_data()
print("node_data")
print(node_data)
if($Player):
print("loading player x")
$Player.global_position.x = node_data["positionx"]
print("loading player y")
$Player.global_position.y = node_data["positiony"]
else:
print("no player to update in world.gd load_game()")
Here is the terminal output that says the player is not loaded.
loading from Input.is_action_just_released(Load)
starting load_game
there is no player in world load_game
node_data
{ “positionx”: 105.187812805176, “positiony”: 51.8545112609863, “score”: 0 }
no player to update in world.gd load_game()
load attempt complete from Input.is_action_just_released(Load)
Here in that code in a Public github repository:
Here is a screenshot of the Autoload:
Here is a screenshot of the Node structure:
I googled and worked on this for 2 days …
Any hints, links or code snippets would be awesome.
Thank you