Skip to content

Instantly share code, notes, and snippets.

@nobnak
Last active April 16, 2021 09:21
Show Gist options
  • Save nobnak/155946559fa441b7b6ae to your computer and use it in GitHub Desktop.
Save nobnak/155946559fa441b7b6ae to your computer and use it in GitHub Desktop.
Quaternion Calculation for Unity
#ifndef __QUATERNION__
#define __QUATERNION__
#define HALF_DEG2RAD 8.72664625e-3
float4 quaternion(float3 normalizedAxis, float degree) {
float rad = degree * HALF_DEG2RAD;
return float4(normalizedAxis * sin(rad), cos(rad));
}
float4 qmul(float4 a, float4 b) {
return float4(a.w * b.xyz + b.w * a.xyz + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz));
}
float3 qrotate(float4 q, float3 v) {
return qmul(qmul(q, float4(v, 0)), float4(-q.xyz, q.w)).xyz;
}
float3 qrotateinv(float4 q, float3 v) {
return qmul(qmul(float4(-q.xyz, q.w), float4(v, 0)), q).xyz;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment