【发布时间】:2011-02-09 11:06:39
【问题描述】:
我正在制作的游戏中有这个脚本。这将在 Blender 游戏引擎中使用。 Blender 不断地从上到下不断地运行脚本,所以如果我在脚本的开头声明一个变量,它就会不断地被初始化。
#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])
基本上,我的问题是在 if 循环中,我将变量从其原始值更改为其旧值的倒数。但是因为我在脚本开头声明了变量的值,所以速度变量不会停留在我将其更改为的值上。
我需要一种方法来永久更改变量的值或只声明一次。
谢谢!
【问题讨论】:
-
旁白:“如果循环”不存在。 “如果”不循环。
-
我认为我们在这里遗漏了一些逻辑。 velocity_x 和velocity_y 的值在结尾和开头肯定是不同的。这一切都包含在一个函数中吗?
-
如果不显示更多代码,就不可能回答您的问题。如所写,您的代码将正常工作。您的代码中有任何功能吗?你在使用
global语句吗? -
“if”语句不是循环。整个脚本在游戏过程中循环。该变量在顶部声明,因此每次脚本再次循环时,该变量都会更改回其原始值。
-
一个小的“pythonic”注释:“velocity_x = (velocity_x * -1)”比“velocity_x *= -1”更漂亮