1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
#include <iostream>
#include <string>
#include <cmath>
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>
class Vector
{
public:
double x{0};
double y{0};
Vector(double x = 0, double y = 0): x(x), y(y){};
~Vector(){};
Vector add(const Vector& other)
{
Vector result;
result.x = this->x + other.x;
result.y = this->y + other.y;
return result;
}
Vector subtract(const Vector& other)
{
Vector result;
result.x = this->x - other.x;
result.y = this->y - other.y;
return result;
}
Vector scale(double scalar)
{
Vector result;
result.x = this -> x * scalar;
result.y = this -> y * scalar;
return result;
}
double magnitude()
{
return sqrt( (x * x) + (y * y) );
}
Vector normalize()
{
Vector result = this->scale(1/this->magnitude());
return result;
}
void draw(Vector& c, SDL_Window *w, SDL_Renderer *r) // RENDER this VECTOR RELATIVE TO c
{
SDL_SetRenderDrawColor(r, 200, 200, 255, SDL_ALPHA_OPAQUE);
SDL_RenderClear(r);
SDL_SetRenderDrawColor(r, 255, 0, 0, SDL_ALPHA_OPAQUE); // RED
SDL_RenderDrawLine(r, c.x, c.y, this->x, this->y);
Vector norm = c.add( (this->subtract(c).normalize()).scale(50) );
SDL_SetRenderDrawColor(r, 0, 255, 0, SDL_ALPHA_OPAQUE); // GREEN
SDL_RenderDrawLine(r, c.x, c.y, norm.x, norm.y);
SDL_RenderPresent(r);
SDL_Delay(2);
char str[80];
sprintf(
str, "Magnitude: %0.1f X: %0.0f Y: %0.0f",
( (this->subtract(c) ).normalize() ).magnitude(),
this->x, this->y
);
SDL_SetWindowTitle(w, str);
}
};
int main(int argc,char* argv[])
{
const int WIDTH = 400;
const int HEIGHT = 300;
SDL_Event event;
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window = SDL_CreateWindow
("FOLLOW THE MOUSE", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
WIDTH, HEIGHT, SDL_WINDOW_OPENGL);
SDL_Renderer *renderer = SDL_CreateRenderer
(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
bool quit = false;
int mouseX{0};
int mouseY{0};
Vector mouse_pos;
Vector center(WIDTH/2, HEIGHT/2);
Vector norm;
while(!quit)
{
SDL_PollEvent(&event);
if(event.type == SDL_QUIT)
break;
SDL_GetMouseState(&mouseX, &mouseY);
mouse_pos.x = mouseX;
mouse_pos.y = mouseY;
mouse_pos.draw(center, window, renderer);
}
return 0;
}
|