"Normalizing" angle directions so they are workable relative to each other. Includes angle_difference and atan2fmod functions as examples.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
AngleNorming/main.cpp

87 lines
2.2 KiB

2 years ago
#define OLC_PGE_APPLICATION
#include "pixelGameEngine.h"
#if defined(__EMSCRIPTEN__)
#include <emscripten.h>
#define FILE_RESOLVE(url, file) emscripten_wget(url, file); emscripten_sleep(0)
#else
#define FILE_RESOLVE(url, file)
#endif
2 years ago
using namespace olc;
2 years ago
const float PI = 3.14159f;
float angle_difference(float angle_1, float angle_2)
{
angle_1=fmod(angle_1,2*PI);
angle_2=fmod(angle_2,2*PI);
float angle_diff = angle_1 - angle_2;
if (angle_diff > PI)
angle_diff -= 2*PI;
else if (angle_diff < -PI)
angle_diff += 2*PI;
return -angle_diff;
}
2 years ago
class Object{
public:
float facing_dir;
float rotation_spd;
vd2d pos;
vd2d size;
Object(vd2d pos, vd2d size, float rotation_spd=100*(3.14159f/180.f), float facing_dir=0)
:pos(pos),size(size),rotation_spd(rotation_spd),facing_dir(facing_dir) {}
void draw(PixelGameEngine*pge) {
pge->DrawCircle(pos,size.x);
pge->DrawLine(pos,{(int)(pos.x+4*cos(facing_dir)),(int)(pos.y+4*sin(facing_dir))});
}
};
2 years ago
// Override base class with your custom functionality
class Example : public olc::PixelGameEngine
2 years ago
{
public:
Example()
{
// Name your application
sAppName = "Rotation";
}
2 years ago
public:
Object*testRotationObj;
bool OnUserCreate() override
{
testRotationObj = new Object({(double)ScreenWidth()/2,(double)ScreenHeight()/2},{8,8});
return true;
}
bool OnUserUpdate(float fElapsedTime) override
{
Clear(BLACK);
float diffAng = atan2f(GetMouseY()-testRotationObj->pos.y,GetMouseX()-testRotationObj->pos.x);
float rotAngle=angle_difference(testRotationObj->facing_dir,diffAng);
if (abs(rotAngle)>testRotationObj->rotation_spd*fElapsedTime) { //Prevents stuttering. Wait for an entire rotation speed amount to occur
if (rotAngle>0) {
testRotationObj->facing_dir+=testRotationObj->rotation_spd*fElapsedTime;
} else {
testRotationObj->facing_dir-=testRotationObj->rotation_spd*fElapsedTime;
}
2 years ago
}
testRotationObj->draw(this);
return true;
}
2 years ago
};
int main()
{
Example demo;
if (demo.Construct(256, 240, 2, 2))
demo.Start();
return 0;
2 years ago
}