我一直有错误
UnboundLocalError:赋值前引用的局部变量'new_speedDx'
在尝试运行以下功能时:
def new_speedD(boid1):
bposx = boid1[0]
if bposx < WALL:
new_speedDx = WALL_FORCE
elif bposx > WIDTH - WALL:
new_speedDx = -WALL_FORCE
bposy = boid1[1]
if bposy < WALL:
new_speedDy = WALL_FORCE
elif bposx > WIDTH - WALL:
new_speedDy = -WALL_FORCE
return new_speedDx, new_speedDy
Run Code Online (Sandbox Code Playgroud)
在这个函数中,boid1是一个有4个元素的向量(xpos,ypos,xvelocity,yvelocity),所有大写的变量都是常量(数字).有人知道如何解决这个问题?我在互联网上找到了许多可能的解决方案,但似乎没有任何工作..
必须有可能bposx既不低于WALL也不高于WIDTH - WALL.
例如:
bposx = 10
WALL = 9
WIDTH = 200
if bposx < WALL: # 10 is greater than 9, does not define new_speedDx
new_speedDx = WALL_FORCE
elif bposx > WIDTH - WALL: # 10 is less than (200 - 9), does not define new_speedDx
new_speedDx = -WALL_FORCE
Run Code Online (Sandbox Code Playgroud)
如果没有看到你的程序的其余部分,很难建议一个合理的回退值,但你可能想要添加如下内容:
else:
new_speedDx = 0
Run Code Online (Sandbox Code Playgroud)