Question

In C# I have the following code:

Vector2.Dot(ref tmpDirection, ref direction, out result);

This returns a float between -1 and 1. I am curious how to get this same functionality in Objective-C. I know you can calculate the dot product of two vectors like so:

CGPoint point1 = CGPointMake(10, 10);
CGPoint point2 = CGPointMake(20, 20);
float dotProduct = point1.x * point2.x + point1.y + point2.y;

What I do not understand is what the C# function does to make the result between -1 and 1 as normal dot product math can result in any number.

Was it helpful?

Solution

All you need to do to get this normalized from [-1,1] is to divide by the product of the magnitudes:

float mag1 = sqrt(point1.x*point1.x + point1.y*point1.y);
float mag2 = sqrt(point2.x*point2.x + point2.y*point2.y);
dotProduct = (dotProduct)/(mag1*mag2);

OTHER TIPS

That is only for unit vectors, from the documentation:

Vector2.Dot Method:

Calculates the dot product of two vectors. If the two vectors are unit vectors, the dot product returns a floating point value between -1 and 1 that can be used to determine some properties of the angle between two vectors. For example, it can show whether the vectors are orthogonal, parallel, or have an acute or obtuse angle between them.

If you wanted to emulate that, you would need to normalize the dot product using the product of the magnitudes of the points. Here's a nice set of functions to achieve such thing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top