如何缩短此代码或使其更高效?

时间:2021-04-16 11:07:01

标签: optimization godot gdscript

我想知道是否有更有效/更短的方法来给出相同的结果。 如果按键被按下,函数 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

3 个答案:

答案 0 :(得分:1)

<块引用>

如果按键被按下,函数 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")

此外,如果参数为 0atan2 将返回 0这是使用 atan2 而不是 atan 的好处之一:您不必担心除以 0因此,您不必担心不需要检查 xy 是否不是 0,只需使用它们。

顺便说一下,y 中的 xatan2 之前。

还有一个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))

答案 1 :(得分:0)

if 的第二个分支可以改成这样:

degValue += -45 * int(Input.get_action_strength("move_right")) + 45 * int(Input.get_action_strength("move_left"))

当值为 False 时,将其转换为 int 时,它变为 0,乘​​法结果为 0。因此只添加一个值。

此外,如果问题被标记为“python”,为什么要使用“var”关键字声明变量? =)

答案 2 :(得分:0)

您可以使用向量并从其分量计算角度:

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°。您可以轻松地将其转换为您需要并认为合适的任何角度值。