For some reason, the mySprite struct moves 2 times faster in the left direction (a key) than the right direction (d key), despite the magnitudes of delta_time
and speed_x
being the exact same when either of the keys is pressed. When this code is run, the logs tell me for a key: -2
and for for d key: 1
. How is this possible?
typedef struct
{
int width;
int height;
int x, y;
pixel *pixels;
bool *mask;
} sprite_t;
sprite_t mySprite;
void update()
{
// Clear the surface
SDL_FillRect(surface, NULL, SDL_MapRGBA(surface->format, 0, 0, 0, 255));
Uint32 *framebuffer = (Uint32 *)surface->pixels;
// Draws pixels to the frame buffer
for (int i = 0; i < mySprite.height; ++i)
{
for (int j = 0; j < mySprite.width; ++j)
{
int pixel_index = (i * mySprite.width + j);
setPixel(framebuffer, mySprite.x + j, mySprite.y + i, rgbaToUint32(&mySprite.pixels[pixel_index]));
}
}
// Reset speed before processing input
speed_x = 0;
speed_y = 0;
if (key_state.w)
{
speed_y = -(SPEED);
}
if (key_state.s)
{
speed_y = SPEED;
}
if (key_state.a)
{
speed_x = -(SPEED);
}
if (key_state.d)
{
speed_x = SPEED;
}
// Halts execution of update until the frame rate reaches target time
int time_to_wait = FRAME_TARGET_TIME - (SDL_GetTicks() - last_frame_time);
if (time_to_wait > 0 && time_to_wait <= FRAME_TARGET_TIME)
{
SDL_Delay(time_to_wait);
}
// Finds difference between last and current frame and divides by 1000 to convert to sec
float delta_time = 0.016f;
last_frame_time = SDL_GetTicks();
int old_pos = mySprite.x;
// Update sprite position
mySprite.x += speed_x * delta_time;
mySprite.y += speed_y * delta_time;
if (key_state.a)
{
printf("for a key: %i n", mySprite.x - old_pos);
}
if (key_state.d)
{
printf("for d key: %i n", mySprite.x - old_pos);
}
}
Tried adding logs to isolate the problem.
They should print:
for a key: -1
for d key: 1
1