Getting a proper rotation from a vector direction

11,689

Solution 1

First of all, in your case, there is no need to convert it to degrees, since Math.aTan2 returns the angle in radians, just divide your rotation variable by (2*Pi).

Secondly, check what you are doing at "t.Width / 2, t.Height / 2", as you haven't specified in your question what 't' is, make sure it's members are not integers.

Now as far as your problem itself, there is not enough information supplied. Where does this contain your rotation information? Is the 'pixelpos' vector your world space position, or do you also use that as rotation?

Brought back to a minimum, the following code works roughly like like you described?

Vector2 pixelpos = new Vector2(0, 1);
float rotation = (float)(Math.Atan2(pixelpos.Y, pixelpos.X) / (2 * Math.PI));

Which results 0.25, or 90 degrees.

Solution 2

The best way to calculate this would be through the use of dot products though:

Vector2 pixelposWorld = Vector2.Normalize(pixelpos - center);
float dot = Vector2.Dot(Vector2.UnitX, pixelposWorld);
float rotation = (pixelposWorld.Y >= 0)
                 ? (1f - dot) / 4f
                 : (dot + 3f) / 4f;

Just saying, it is on average 120% faster (I ran the tests).

Share:
11,689
user0
Author by

user0

Updated on June 05, 2022

Comments

  • user0
    user0 almost 2 years

    I currently have this code in my game:

    Vector2 pixelpos = new Vector2(x, y);
    Vector2 center = new Vector2(t.Width / 2, t.Height / 2);
    
    Vector2 pixelposWorld = (pixelpos - center);
    
    float rotation = (float)Math.Atan2(pixelposWorld.Y, pixelposWorld.X);
    float rotationPercent = (MathHelper.ToDegrees(rotation) / 360);
    

    My goal is to end up with rotationPercent to be a value between 0.0 and 1.0, 0 degrees being 0.0, 180 being 0.5 and 360 being 1.0.

    Currently, rotationPercent only comes out as 1.0.

    What can I do to fix this?

  • Marking
    Marking over 12 years
    No, although I agree he should make it a float for a proper code style, the function MathHelper.ToDegrees() returns a float and the compiler will implicit convert 360 to a const float.
  • user0
    user0 over 12 years
    Yeah, it worked, Thanks! All I needed to do was get the result and add 0.5f to it. The t variable was a Texture2D, the point of this code is to generate a circle into a texture, which I had working. What I am trying to implement now is the ability to have different heights around the circle, so I need the rotation of each pixel to tell what height that point should be from an array of float values. Thanks, and please wish me luck on implementing the rest.