Created
July 18, 2026 07:41
-
-
Save jweinst1/7675a6581f13639467d75bd9b78781ef to your computer and use it in GitHub Desktop.
draw a circle with sin and cos in C++ SDL3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <SDL3/SDL.h> | |
| #include <SDL3/SDL_main.h> | |
| #include <cmath> | |
| // Calculates the X and Y screen coordinates for a circle centered anywhere | |
| void get_arbitrary_circle_point_trig( | |
| float centerX, float centerY, | |
| float radius, float angle_radians, | |
| float* out_x, float* out_y | |
| ) { | |
| // 1. Calculate the local x distance, then shift it by the center X | |
| *out_x = centerX + (radius * cosf(angle_radians)); | |
| // 2. Calculate the local y distance, then shift it by the center Y | |
| *out_y = centerY + (radius * sinf(angle_radians)); | |
| } | |
| void gen_circle_points(float centerX, | |
| float centerY, | |
| float radius, | |
| SDL_FPoint* points) { | |
| int total_steps = (int)(2.0f * SDL_PI_F * radius); | |
| float angle_step = (2.0f * SDL_PI_F) / total_steps; | |
| for (int i = 0; i < total_steps; i++) | |
| { | |
| float angle = i * angle_step; | |
| float x, y; | |
| get_arbitrary_circle_point_trig(centerX, centerY, radius, angle, &x, &y); | |
| points->x = x; | |
| points->y = y; | |
| ++points; | |
| } | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| bool quit = false; | |
| SDL_Window *window = SDL_CreateWindow("Triangle Example", 800, 600, 0); | |
| SDL_Renderer *renderer = SDL_CreateRenderer(window, NULL); | |
| static constexpr float centerX = 400.0f; | |
| static constexpr float centerY = 300.0f; | |
| static constexpr float circleRads = 40.0f; | |
| static constexpr int circlePointCount = (int)(2.0f * SDL_PI_F * circleRads); | |
| SDL_FPoint topPoints[circlePointCount]; | |
| gen_circle_points(centerX, centerY, circleRads, topPoints); | |
| while (!quit) { | |
| SDL_Event ev; | |
| while (SDL_PollEvent(&ev) != 0) { | |
| switch(ev.type) { | |
| case SDL_EVENT_QUIT: | |
| quit = true; | |
| break; | |
| } | |
| } | |
| SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); | |
| SDL_RenderClear(renderer); | |
| SDL_SetRenderDrawColor(renderer, 233, 0, 0, 255); | |
| SDL_RenderPoints(renderer, topPoints, circlePointCount); | |
| SDL_Delay(16); | |
| SDL_RenderPresent(renderer); | |
| } | |
| SDL_DestroyRenderer(renderer); | |
| SDL_DestroyWindow(window); | |
| SDL_Quit(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment