Skip to content

Instantly share code, notes, and snippets.

@Vavassor
Created March 20, 2019 21:23
Show Gist options
  • Select an option

  • Save Vavassor/2dd8d4dfdf36598bef4fb6c242132555 to your computer and use it in GitHub Desktop.

Select an option

Save Vavassor/2dd8d4dfdf36598bef4fb6c242132555 to your computer and use it in GitHub Desktop.
Rotate a 2D vector by i turns of 90 degrees.
#include <math.h>
#include <stdio.h>
typedef union Float2
{
struct
{
float x;
float y;
};
float e[2];
} Float2;
// Rotate a 2D vector by i turns of 90 degrees.
Float2 rotate(Float2 v, int i)
{
Float2 result;
const float ones[2] = {1.0f, -1.0f};
int j = i + 1;
int x_index = i & 1;
int y_index = j & 1;
float sign_x = ones[(i & 2) >> 1];
float sign_y = ones[(j & 2) >> 1];
result.x = copysignf(v.e[x_index], sign_x);
result.y = copysignf(v.e[y_index], sign_y);
return result;
}
int main(int argc, const char** argv)
{
Float2 arm = {0.2f, 0.5f};
for(int i = -4; i < 4; i += 1)
{
Float2 spun = rotate(arm, i);
printf("<%f, %f>\n", spun.x, spun.y);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment