Mark
Mark

Reputation: 14930

C# Vector maths questions

Im working in a screen coordinate space that is different to that of the classical X/Y coordinate space, where my Y direction goes down in the positive instead of up.

Im also trying to figure out how to make a Circle on my screen always face away from the center point of the screen.

If the center point of my screen is at x(200) y(300) and the point of my circle's center is at x(150) and y(380) then I would like to calculate the angle that the circle should be facing.

At the moment I have this:

        Point centerPoint = new Point(200, 300);
        Point middleBottom = new Point(200, 400);

        Vector middleVector = new Vector(centerPoint.X - middleBottom.X, centerPoint.Y - middleBottom.Y);

        Vector vectorOfCircle = new Vector(centerPoint.X - 150, centerPoint.Y - 400);

        middleVector.Normalize();
        vectorOfCircle.Normalize();

        var angle = Math.Acos(Vector.CrossProduct(vectorOfCircle, middleVector));

        Console.WriteLine("Angle: {0}", angle * (180/Math.PI));

Im not getting what I would expect.

I would say that when I enter in x(150) and y(300) of my circle, I would expect to see the rotation of 90 deg, but Im not getting that... Im getting 180!!

Any help here would be greatly appreciated.

Cheers, Mark

Upvotes: 1

Views: 2782

Answers (3)

Maciej Hehl
Maciej Hehl

Reputation: 7985

One remark:

The cos-sinus function is used in the dot product. Cross product uses sinus.

Upvotes: 1

Mark
Mark

Reputation: 14930

Its ok, I think I got it now:

I read this article:

http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/index.htm

Which identified that I needed to use Atan2 instead of acos

        Point centerPoint = new Point(200, 300);
        Point middleBottom = new Point(200, 400);

        Vector middleVector = new Vector(centerPoint.X - middleBottom.X, centerPoint.Y - middleBottom.Y);
        Vector vectorOfCircle = new Vector(centerPoint.X - 250, centerPoint.Y - 300);

        middleVector.Normalize();
        vectorOfCircle.Normalize();

        var angle = Math.Atan2(vectorOfCircle.Y, vectorOfCircle.X) - Math.Atan2(middleVector.Y, middleVector.X);

        Console.WriteLine("Angle: {0}", angle * (180/Math.PI));

Upvotes: 1

Guffa
Guffa

Reputation: 700322

No, that is correct. The zero angle is from origo (centerPoint) out to the right. As the circle is to the left of origo, then angle is 180 degrees.

Upvotes: 0

Related Questions