1
$\begingroup$

I am using version 2.79.
How can I save and load an objects position in the BGE?

$\endgroup$
1
  • $\begingroup$ If my answer helped you, please accept it. If not, just ask with more details. $\endgroup$
    – Joel Gomes
    Jun 4, 2019 at 19:09

1 Answer 1

4
$\begingroup$

To save, you only need to:

  • Get the object's attributes

  • Store them in a dictionary

  • Convert this dictionary to string

  • Write the resulting data to disk

To load this data, you only need to:

  • Read this saved data

  • Convert the loaded string to dictionary

  • Set the object's attributes

Here's a working script (below) and a example blend file. Press 1 to load and 2 to save on the example blend file.

Press 1 to load and 2 to save on the example blend file

import bge
from ast import literal_eval

def save(cont):

    # Objects
    own = cont.owner

    # Sensors
    sensor = cont.sensors[0]

    # Properties
    path = bge.logic.expandPath('//')
    savedata = {
        'position' : list(own.worldPosition),
        'rotation' : list(own.localOrientation.to_euler())
    }

    ### PROCESS ###
    if sensor.positive:

        # Creates/overwrites savedata file
        with open(path + 'savedata.sav', 'w') as openedfile:

            # Write savedata dict as str
            openedfile.write(str(savedata))
            print('Data saved to ' + openedfile.name)

def load(cont):

    # Objects
    own = cont.owner

    # Sensors
    sensor = cont.sensors[0]

    # Properties
    path = bge.logic.expandPath('//')
    savedata = None

    ### PROCESS ###
    if sensor.positive:

        try:
            # Try to open savedata file
            with open(path + 'savedata.sav', 'r') as openedfile:

                # Reads savedata and evaluates it from str to dict
                savedata = literal_eval(openedfile.read())
                print('Loaded data from ' + openedfile.name)

            # Set object attributes from loaded data
            own.worldPosition = savedata['position']
            own.localOrientation = savedata['rotation']

        except FileNotFoundError:
            print('Save data not found')
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .