Python typeerror'float'对象不是callab

2024-04-28 14:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我用python编写了一个程序,我有一些点,在一个按键上,我需要让它们沿着轴旋转,所以按x,它将围绕x轴旋转,按y,表示y,按z,表示z

我很确定我的代码布局是正确的 首先我定义我的旋转值

x_rot = 1
y_rot = 1
z_rot = 1

接下来我设置我的数学值:

   #setup angles for rotation
angle = 1
rad = angle * math.pi / 180
cose = math.cos(rad)
sine = math.sin(rad)

然后,我按照以下格式在名为Xs、Ys和Zs的列表中设置我的x y和z点:

   Xs=(12.0, 25.0, 10.0, 22.0)
   Ys=(2.0, 15.0, 12.0, 27.0) 
   Zs=(21.0, 23.0, 1.0, 12.0) 

下一步,我设置我的按键,使我的坐标值乘以一个旋转矩阵,这样当我按下键盘上的x按钮时,我的点就围绕x轴旋转。

done = False

while done == False:
    # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done = True # Flag that we are done so we exit this loop
            # User pressed down on a key

        elif event.type == pygame.KEYDOWN | event.type == pygame.KEYUP:
             if event.key == pygame.K_x:
                y_rot == Ys*cose(angle)-Zs*(angle)
                z_rot == Ys*sine(angle)-Zs*cose(angle)
                x_rot == Xs

然后我运行我的代码,它工作正常,直到我按x按钮旋转它。当我按下按钮时,我会说一个错误

typeerror 'float' object is not callable

它引用了这一行

y_rot == Ys*cose(angle)-Zs*(angle)

我有一种感觉,这是一个简单的解决办法,但我只是想不出它可能是什么。


Tags: 代码eventtypemath按钮pygame按键xs
3条回答

您为cose分配了一个浮点值:

cose = math.cos(rad)

然后尝试将该值用作带cose(angle)的函数:

y_rot == Ys*cose(angle)-Zs*(angle)

这一行有更多的错误,但是让我们首先关注cose(angle)。如果要将其用作乘法,请执行以下操作:

Ys * cose * angle - Zs * angle

括号只在这里起到混淆作用;只有在需要对表达式进行分组时才使用它们。

请注意,==是对相等性的测试;如果要赋值,请使用单个=等于:

y_rot = Ys * cose * angle - Zs * angle
z_rot = Ys * sine * angle - Zs * cose * angle
x_rot = Xs

如果YsZs元组,则需要分别将其应用于元组的每个元素:

y_rot = tuple(y * cose * angle - z * angle for y, z in zip(Ys, Zs))
z_rot = tuple(y * sine * angle - z * cose * angle for y, z in zip(Ys, Zs))
x_rot = Xs

对于您声明的值YsZs给出:

>>> tuple(y * cose * angle - z * angle for y, z in zip(Ys, Zs))
(-19.000304609687216, -8.002284572654132, 10.998172341876696, 14.995887769222563)
>>> tuple(y * sine * angle - z * cose * angle for y, z in zip(Ys, Zs))
(-20.96189678540965, -22.734710892037747, -0.7904188179089892, -11.526957368070041)

我不太熟悉这里如何计算旋转矩阵;我已经为每个计算配对了YsZs元组元素;但我怀疑计算更复杂。更重要的是,你不能仅仅用一个浮点数乘以一个元组,希望正确的计算能够实现。

你编码那部分的方式是说cose是一个带参数的函数angle

cose(angle) 


y_rot == Ys*cose*(angle)-Zs*(angle)
                ^
                |
            Maybe you are missing this.

按照您定义cose的方式,它立即计算math.cos(rad)的值,并将浮点结果分配给cose。然后你试着调用cose(angle),这和调用2.7(angle)基本上是一样的,也就是说,这是无稽之谈。

我想你想要这样的东西:

def cose(angle):
    angle = 0
    rad = angle * math.pi / 180
    return math.cos(rad)

def sine(angle):
    angle = 0
    rad = angle * math.pi / 180
    return math.sin(rad)

不过,如果这个degree/radian转换还没有内置到Python中,我会感到惊讶。

相关问题 更多 >