I’m trying to do some polygon rotation in Pygame, so I’m doing some dot products and getting radians and applying acos to those radians. According to this link I should use a clamp function to keep the dot product between -1 and 1. However, I get the following error:
d_p = (clamp(self.dot_product(other), -1.0, 1.0))
NameError: global name 'clamp' is not defined
They appear to be in the same namespace – this is exactly as they appear in the code. I have tried using @staticmethod on clamp() but it stays the same. The only thing that works is to make it an instance method (signature clamp(self, x, a, b) but this seems like a bad solution when clamp doesn’t need to know about a specific instance. What is the right way to fix this, and what concept am I missing?
class v2:
#...
def clamp(x, a, b):
return min(max(x, a), b)
def radians_between(self, other):
d_p = (clamp(self.dot_product(other), -1.0, 1.0))
cos_of_angle = d_p/(self.get_magnitude()*other.get_magnitude())
return math.acos(cos_of_angle)
In order to fix this, you must use
self.clamp()when using it inside of the class that it is defined in. Otherwise you must usev2.clamp()if you are calling it from outside of the class.The reason it is saying
global name 'clamp' is not definedis because it thinks that ‘clamp’ is supposed to be a variable,function, or class in the global scope such as:or:
or finally: