I am attempting to get a gun to rotate around the player based on a vector2 input
if the y component of the vector is positive it works perfectly as you can see here
Working as intended (Ignore my placeholder graphics)
if the y component is negative however, it returns the same value as if the y value was positive
I'm sure this has to do with the equation I'm using, in particular the fact that the y component is removed from the equation when multiplied by the y component in my base vector, but other methods I've used only make things worse, usually causing the gun to not rotate at all while the y value is negative.
static u16 vector2To512Ang(vector2 v) {
// Avoid division by zero
if (v.getMagnitude() == 0)
return 0;
// Base vector
vector2 b = {1, 0};
float angle = acos((v.x * b.x v.y * b.y)/abs(v.getMagnitude())) * 57.2957795131f;
// Convert to scale of 0-512
return (angle * 512) / 360;
}
To clear up any questions
- The scale of the output is weird because I'm working with old hardware and it needs a range of 0-512. Removing this scaling results in the same issue so that isn't the problem
- The multiplication by 57.2957795131 is the same as 180 / PI precomputed and is done to convert from radians to degrees
CodePudding user response:
I'm unsure what you're after but I think you want the angle between v.x
and v.y
scaled to 0-512
. In that case:
#include <cmath>
#include <numbers>
// ...
float angle = std::atan2(v.y, v.x);
if(angle < 0.) angle = 2 * std::numbers::pi_v<float>;
return angle * 512 / (2 * std::numbers::pi_v<float>);
// return angle * 256 / std::numbers::pi_v<float>;