Thanks!
I've written this code.
Maybe someone could comment if he/she see something that could be improved.
Otherwise it will perhaps be usefull for someone else :-)
#include <math.h>
sfVector2f sfJoystick_normaliseDirectionProportional(float x, float y)
{
#define VECTOR_LENGTH(x, y) \
sqrtf(((x) * (x)) + ((y) * (y)))
float angle, in_len, max_len, max_x, max_y, ratio, norm_x, norm_y;
sfVector2f res;
if (x == 0.f && y == 0.f) {
res.x = 0.f;
res.y = 0.f;
return res;
}
angle = atan2f(y, x);
in_len = VECTOR_LENGTH(x, y);
if (fabsf(x) > fabsf(y)) {
max_x = 100.f;
max_y = max_x * y / x;
} else {
max_y = 100.f;
max_x = max_y * x / y;
}
max_len = VECTOR_LENGTH(max_x, max_y);
ratio = in_len / max_len;
norm_x = cosf(angle);
norm_y = sinf(angle);
res.x = norm_x * ratio;
res.y = norm_y * ratio;
return res;
#undef VECTOR_LENGTH
}
Hi,
It seems that the previous code can be simpilfied, this version seems to produce the same results without needing to calculate the angle. Here we save calling atan2, cos and sin:
sfVector2f
sfJoystick_normaliseDirectionProportional(float x, float y)
{
#define VECTOR_LENGTH(x, y) \
sqrtf(((x) * (x)) + ((y) * (y)))
float in_len, ratio;
sfVector2f res;
if (x == 0.f && y == 0.f) {
res.x = 0.f;
res.y = 0.f;
return res;
}
in_len = VECTOR_LENGTH(x, y);
if (fabsf(x) > fabsf(y))
ratio = fabsf(x / 100.f) / in_len;
else
ratio = fabsf(y / 100.f) / in_len;
res.x = x * ratio;
res.y = y * ratio;
return res;
#undef VECTOR_LENGTH
}
again please comment if you can :)