Vector Rotation

Print
User Rating:  / 0
PoorBest 
Category: Beginner
Created on Monday, 27 June 2011 Published Date Written by MindYourByte

deDieser Beitrag steht auch in Deutsch zur Verfügung, schaue ihn dir hier an!

Step 1: Rotationdefinition

As Base we are using the Dot Product for the calculation:

vec{a}*vec{b}=delim{|}{vec{a}}{|}*delim{|}{vec{b}}{|}*Cos(alpha)

For vec{a} we are using ({1}under{0}) (which has a Rotation of 0). Therefore we have got following simplification:

{1*b_0+0*b_1}/{sqrt{1^2+0^2}*sqrt{{b_0}^2+{b_1}^2}}=Cos(alpha)

doubleleftright{b_0}/{sqrt{{b_0}^2+{b_1}^2}}=Cos(alpha)

doubleleftright ACos({{b_0}/{sqrt{{b_0}^2+{b_1}^2}}})=alpha

Because we've got an Square Root in the calculation these values are only for positive Y-Values of the Vector vec{b}. To implement negative Y-Values we just simply negate the result whether we have a negative Y-Value.

Step 2: Code Implementation

The Implementation is in C#/XNA very simple because the length of the Vector is given through the .Length method:

rotation = (float)Math.Acos(b.X / (b.Length()));
            if (b.Y < 0)
                rotation = -rotation;

Step 3: Extensions

To simplify the access to the Method we implement the formula as Extension (siehe Extensions) of the Vector2 struct:

public static class Vector2Extensions //Remark: Static Class
    {
        /// 
        /// Returns the Angle of the Vector2
        public static float GetRotation(this Vector2 v) 
        //Remark: Static Method and first Parameter must be >>this Vector2<<
        {
            float rotation;
            rotation = (float)Math.Acos(v.X / (v.Length()));
            if (v.Y < 0)
                rotation *= -1;
            return rotation;
            
        }
    }

With this code we can directly acces the Rotation as follows:

written by Marvin Pohl aka MindYourByte

Copyright 2011. Joomla 1.7 templates free.
Valid XHTML 1.0