I am trying to find angle between vectors a and b. But the cosine for some reason is not within +/- 1, that means that it is not possible to find an angle between a car and a pedestrian...
Any help appreciated
EDIT I have rewritten my function in accordance with the answer below (I had to do some changes due to writing in Python, for example pedestrian.body.position is equivalent to body.GetPosition()
I also tried to normalize both vectors, but the cosine is still not within +/- 1 And the car can move in both direction, so I do not know how to get its other component...
def detect_pedestrian(car,pedestrian):
#Find a vector which connects pedestrian with a car
pedestrian_position = pedestrian.body.position
car_position = car.body.position
#Find vectors a and b
car_vector = Box2D.b2Body.__GetTransform(car.body).R.GetYAxis()
pedestrian_vector = pedestrian_position - car_position
#Calculate magnitudes of both vector
pedestrian_vector_magnitude = np.linalg.norm(pedestrian_vector)
car_vector_magnitude = np.linalg.norm(car_vector)
#Normalize both vectors
pedestrian_vector_normalized = pedestrian_vector/pedestrian_vector_magnitude
car_vector_normalized = car_vector/car_vector_magnitude
#Calculate angle
magnitudes = pedestrian_vector_magnitude * car_vector_magnitude
dot_product = b2Dot(pedestrian_vector_normalized, car_vector_normalized)
cosine = magnitudes/dot_product
arccos = np.arccos(cosine)
print(cosine)
```