15,964,238 members
1.00/5 (1 vote)
See more:
Hello Codeproject,

Let's assume I have two vector points.

C#
```/* Vectors to begin angle calculation. */
Vector2 PointStart = new Vector2(Room.Width / 2, Room.Height / 2);
Vector2 PointMouse = new Vector2(Mouse.X, Mouse.Y);

/* Set the angle. */
Angle = Angle.From(PointStart, PointMouse);```

I have however attempted this:
C#
```/* Get Angle between void. */
/// <summary>
/// Retrieves the angle between two points(Vectors).
/// </summary>
/// <param name="i">The starting vector.</param>
/// <param name="j">The point to the other vector(12 o' clock)</param>
/// <returns></returns>
public float AngleToMouse(Vector2 Mouse)
{
/* Delta */
DeltaPoint = new Vector2((this.PositionX + Mouse.X) - this.PositionX, (this.PositionY + Mouse.Y) - this.PositionY);

/* Return */
return (float)(Math.Atan2(DeltaPoint.Y, DeltaPoint.X) * 180 / Math.PI);
}
```

But the result was:

[^]

How would I do the above?

- Riberto
Posted
Updated 24-Feb-13 4:23am
v2
Sandeep Mewara 24-Feb-13 11:15am
And what exactly is the issue and not working? I opened up the image but it did not say anything about the issue.
Yvar Birx 24-Feb-13 13:09pm
Oh, I didn't notice that there was no cursor. Anyways, my cursor is in the down left corner, and it's looking at the other side.
Philippe Mori 24-Feb-13 22:35pm
The computation of DeltaPoint look wrong. I'm not sure of what angle you want so it somewhat hard to answer.

## Solution 2

Calculating degrees fails![^].

—SA

## Solution 1

I would use the scalar product formula, namely `v1 . v2 = |v1| |v2| cos(phi)`.
Hence `phi = arccos( x1*x2+y1*y2/sqrt(x1*x1+y1*y1)/sqrt(x2*x2+y2*y2))`.

C#
```public double Angle(Vector2 v1, Vector2 v2)
{
double v1m = Math.Sqrt(v1.X*v1.X+v1.Y*v1.Y);
double v2m = Math.Sqrt(v2.X*v2.X+v2.Y*v2.Y);
double angle = 180 * Math.PI * Math.Acos(( v1.X*v2.X+v1.Y*v2.Y ) / v1m / v2m);
return angle;
}
```

Yvar Birx 24-Feb-13 16:14pm
This returns as NaN?
CPallini 24-Feb-13 16:45pm
It shouldn't. What are your input values?
Yvar Birx 25-Feb-13 1:47am
public void DoMouse()
{
/* Mouse State */
MouseState State = Mouse.GetState();

/* Set the Angle. */
World.Player.SetAngle(World.Player.AngleBetweenCooardinates(new Vector2(State.X, State.Y), new Vector2(World.Player.PositionX, World.Player.PositionY)));
}
Sergey Alexandrovich Kryukov 24-Feb-13 19:15pm
Carlo, you should use different expression, depending on quadrant. Even if the acos value is defined, it causes Loss of Presicion, if you do it wrong. You should first compare X*X with Y*Y and make a decision accordingly.
—SA
CPallini 25-Feb-13 5:25am
Are you kidding?