Pregunta

Tengo este script en un juego que estoy haciendo. Esto será utilizado en el motor de juego de Blender. Blender ejecuta secuencias de comandos y otra vez de arriba a abajo de forma continua, por lo que si declaro una variable al principio de la secuencia de comandos, que sigue siendo inicializado una y otra vez.

#The current location of the object
loc_x = obj.getPosition()[0]
loc_y = obj.getPosition()[1]

#The velocity of the object
velocity_x = 0.09
velocity_y = 0.03


#If the location of the object is over 5, bounce off.
if loc_x > 5:
    velocity_x = (velocity_x * -1)

if loc_y > 5:
    velocity_y = (velocity_y * -1)

#Every frame set the object's position to the old position plus the velocity
obj.setPosition([(loc_x + velocity_x),(loc_y + velocity_y),0])

Básicamente, mi problema es que en el caso de bucles, puedo cambiar la variable de su valor original a la inversa de su antiguo valor. Pero debido a que declaro el valor de la variable al principio de la secuencia de comandos, las variables de velocidad no se quedan en lo que lo cambio a.

Necesito una manera de cambiar el valor de la variable de forma permanente o declarar una sola vez.

Gracias!

¿Fue útil?

Solución

Para manejar el bucle continuo a través de su código de secuencias de comandos que necesita un valor que fuera ist escrito del código. De lo contrario, no puede trabajar. ¿Cómo debe saber que su guión que ha sido ejecutado antes? Siguiendo ejecuta código con Blender 2.6 y 2.7 serie:

Posibilidad 1:. Licuadoras Diccionario Global añadir un Subdictionary (se puede vaciar también):

bge.logic.globalDict['mysubdictionaryName'] = { 'namestring' : False}

Puede guardar los valores de esta manera: bge.globalDict['mysubdictionaryName'] = myValue.

Posibilidad 2: OBJECTPROPERTY a) con el pitón:

myObject = bge.logic.getCurrentController().owner

myObject['myproperty_named_has_run_before'] = True

b) Uso Logicbricks y añadir propiedades dentro de la lógica-editor

En el caso de que se utilice ObjectProperties, ya que se utiliza el globalDict, cuando varios objetos se comunican o si tienen que tomar los datos a otro gamescene.

Otros consejos

Ponga las declaraciones velocity_x y velocity_y antes del bucle. Si está utilizando las clases, hacer que los atributos del objeto y intialize sólo una vez, en el interior de su __init__().

EDIT: No sé cómo funciona el motor de juego de Blender, pero además de tener el guión en un lazo grande, debe haber una manera de inicializar cosas antes de que comience el bucle. En realidad, eso es todo lo que puedo decir dado mi limitado conocimiento de su situación específica.

MI busca de la respuesta de la misma pregunta. hay una manera de que me coould find.u debe hacer clic en el botón "Agregar propiedad" y añadir una propiedad en la licuadora UI.for ejemplo, una sola vez = False.

A continuación, en la escritura de guión:

si sola vez == Falso:      Hacer eventos.      Onetime = True

esta es la única manera de que pudiera encontrar.

Si el entorno de tiempo de ejecución Python es el mismo cada vez que se ejecuta el script trate de mover su inicialización a un manejador de excepciones. De esta manera:

try:
    velocity_x = (velocity_x * -1)
except:
    velocity_x = 0.09

También puede probar el relleno de la variable en el módulo __main__ si eso no funciona. De esta manera:

try:
    __main__.velocity_x = (velocity_x * -1)
except:
    __main__.velocity_x = 0.09

Si eso no funciona, usted necesitará algo ligero y construido en el módulo como sqlite3. He reescrito todo el fragmento de código:

import sqlite3

#The current location of the object
loc_x = obj.getPosition()[0]
loc_y = obj.getPosition()[1]

c = sqlite3.connect('/tmp/globals.db')
#c = sqlite3.connect('/dev/shm/globals.db')
# Using the commented connection line above instead will be
# faster on Linux. But it will not persist beyond a reboot.
# Both statements create the database if it doesn't exist.

# This will auto commit on exiting this context
with c:
    # Creates table if it doesn't exist
    c.execute('''create table if not exist vectors 
      (vector_name text primary key not null, 
       vector_value float not null,
       unique (vector_name))''')

# Try to retrieve the value from the vectors table.
c.execute('''select * from vectors''')
vector_count = 0
for vector in c:
    vector_count = vector_count + 1
    # sqlite3 always returns unicode strings
    if vector['vector_name'] == u'x':
        vector_x = vector['vector_value']
    elif vector['vector_name'] == u'y':
        vector_y = vector['vector_value']

# This is a shortcut to avoid exception logic
# Change the count to match the number of vectors
if vector_count != 2:
    vector_x = 0.09
    vector_y = 0.03
    # Insert default x vector. Should only have to do this once
    with c:
        c.executemany("""replace into stocks values 
          (?, ?)""", [('x', vector_x), ('y', vector_y)])

#If the location of the object is over 5, bounce off.
if loc_x > 5:
    velocity_x = (velocity_x * -1)
if loc_y > 5:
    velocity_y = (velocity_y * -1)

# Update stored vectors every time through the loop
with c:
    c.executemany("""update or replace stocks set vector_name = ?, 
      vector_value = ?)""", [('x', vector_x), ('y', vector_y)])

#Every frame set the object's position to the old position plus the velocity
obj.setPosition([(loc_x + velocity_x),(loc_y + velocity_y),0])

# We can also close the connection if we are done with it
c.close()

Sí, podría ser sintonizado en funciones o clases de fantasía, pero si ese es el alcance de lo que está haciendo no es necesario mucho más que eso.

Un ejemplo del uso global.

#The velocity of the object
velocity_x = 0.09
velocity_y = 0.03
loc_x = 0
loc_y = 0    

def update_velocity():  
  #If the location of the object is over 5, bounce off.
  global velocity_x, velocity_y
  if loc_x > 5:
    velocity_x = (velocity_x * -1)

  if loc_y > 5:
    velocity_y = (velocity_y * -1)

def update_position():
  global loc_x, loc_y # global allows you to write to global vars
                      # otherwise you're creating locals :)
  loc_x += velocity_x
  loc_y += velocity_y     

#Every frame set the object's position to the old position plus the velocity

while True:
  update_velocity()
  update_position()
  # undoubtedly you do more than this...
  obj.setPosition([loc_x,loc_y,0])

Editar

vi un __init__ en algunos comentarios. Si estás en una clase no hay que escribir algo como:

self.loc_x += self.velocity_x

y así sucesivamente, para hacer referencia a la instancia?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top