如何解决如何缩短此代码或使其更高效?
我想知道是否有更有效/更短的方法来给出相同的结果。 如果按键被按下,函数 get_action_strength(action) 返回一个布尔值, 谢谢。
var degValue = 0
if (Input.get_action_strength("move_forward")):
degValue = 0
if (Input.get_action_strength("move_right")):
degValue += -45
if (Input.get_action_strength("move_left")):
degValue += 45
elif (Input.get_action_strength("move_backward")):
degValue = 180
if (Input.get_action_strength("move_right")):
degValue -= -45
if (Input.get_action_strength("move_left")):
degValue -= 45
else:
if (Input.get_action_strength("move_right")):
degValue = -90
if (Input.get_action_strength("move_left")):
degValue = 90
解决方法
如果按键被按下,函数 get_action_strength(action) 返回一个布尔值
不,没有。 get_action_strength
返回浮点数。您可以充分利用这一点。
你可以这样做:
var x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
var y = Input.get_action_strength("move_forward") - Input.get_action_strength("move_backward")
此外,如果参数为 0
,atan2
将返回 0
。 这是使用 atan2
而不是 atan
的好处之一:您不必担心除以 0
。因此,您不必担心不需要检查 x
和 y
是否不是 0
,只需使用它们。
顺便说一下,y
中的 x
在 atan2
之前。
还有一个rad2deg
函数,如果你有弧度并且想要度数:
var x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
var y = Input.get_action_strength("move_forward") - Input.get_action_strength("move_backward")
var degValue = rad2deg(atan2(y,x))
如果你真的想要,你可以内联变量,这将是一个单行。
啊,抱歉,我可能误会了。你希望它是离散的,对吧?你想要ceil
:
var x = ceil(Input.get_action_strength("move_right")) - ceil(Input.get_action_strength("move_left"))
var y = ceil(Input.get_action_strength("move_forward")) - ceil(Input.get_action_strength("move_backward"))
var degValue = rad2deg(atan2(y,x))
,
if 的第二个分支可以改成这样:
degValue += -45 * int(Input.get_action_strength("move_right")) + 45 * int(Input.get_action_strength("move_left"))
当值为 False 时,将其转换为 int 时,它变为 0,乘法结果为 0。因此只添加一个值。
此外,如果问题被标记为“python”,为什么要使用“var”关键字声明变量? =)
,您可以使用向量并从其分量计算角度:
motion_vec_x = 0
motion_vec_y = 0
if (Input.get_action_strength("move_forward")):
motion_vec_y = 1
if (Input.get_action_strength("move_backward")):
motion_vec_y = -1
if (Input.get_action_strength("move_left")):
motion_vec_x = -1
if (Input.get_action_strength("move_right")):
motion_vec_x = 1
degValue = None
if abs(motion_vec_x) > 0 or abs(motion_vec_y) > 0:
degValue = np.arctan2(motion_vec_x,motion_vec_y) / np.pi * 180
print(degValue
这将产生(取决于 arctan2 实现)向上为 0°,向左倾斜的向量为负度数,向右倾斜的向量为正值。直接向下指向将是 180°。您可以轻松地将其转换为您需要并认为合适的任何角度值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。