[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Pygame 2D vector



On 23.07.2011 13:03, sam.hacking@xxxxxxxx wrote:
On the 2D vector page, http://pygame.org/wiki/2DVectorClass
 
It has a get_angle() function, the first line of this checks if length_sqrd() == 0, and then returns the angle as 0. This seems wrong to me, if the vector is (1,-1), then length_sqrd (1**2 + -1**2) returns 0, and so the angle is returned as 0. The angle for the vector should return -0.78... (in radians) not 0.
 
I believe the problem is get_length_sqrd(), I think the lines:
x = -self.x if self.x < 0 else self.x
y = -self.y if self.y < 0 else self.y
should be added (and the same to get_length()). I just wanted to check if people agree, before I change the page.
 
I assume this function call is supposed to be faster that math.atan2, which is why it is checked first. With these extra lines of code, is it still beneficial to have this call in, or just to remove the call from get_angle()?
 
Thanks,
Sam Bull

Hi Sam

I think your math is wrong:

length_sqrd (1**2 + -1**2) returns 0          <--btw this line does not make much sense anyway, it should be length_sqrd(1, -1)


this is not true, calculated correctly:

1** 2 + -1 ** 2  ==  1 * 1 + -1 * -1 == 1 + 1 == 2


Your mistake basically was that you assumed that  -1 ** 2 == -1 which is not.

And I think the check in which quadrant the point is should be done in the get_angle method since get_length_sqrd just returns the length of a vector which does not depend on the quadrant. Using atan2 might be simpler but could not match with the angles pygame uses (besides of the potentially needed degree <-> radians translations).

Hope this helps.

~DR0ID