The following program is supposed to:
- Draw 2 rectangles on two sides of the screen.
- Move the left rect up and down according to the up and down finger movement in the left half of the touch device.
- Move the right rect up and down according to the up and down finger movement in the right half of the touch device.
#include <SDL2/SDL.h>
int main(int argc, char* argv[])
{
SDL_Init(SDL_INIT_VIDEO);
SDL_DisplayMode dm;
SDL_GetCurrentDisplayMode(0, &dm);
int w{dm.w}, h{dm.h};
SDL_Window* window = SDL_CreateWindow("Movement", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_FULLSCREEN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Rect rect1;
rect1.x = w/8;
rect1.y = h/2;
rect1.w = 50;
rect1.h = 50;
SDL_Rect rect2{w/8*7, h/2, 50, 50};
int middlescreenx = w/2;
int initialTouchY1 = 0;
int initialTouchY2 = 0;
while (1)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
case SDL_FINGERDOWN:
if (event.tfinger.x <= middlescreenx)
{
initialTouchY1 = event.tfinger.y;
}
else
{
initialTouchY2 = event.tfinger.y;
}
break;
case SDL_FINGERMOTION:
if (event.tfinger.fingerId == 0) // First finger
{
int deltaY = event.tfinger.y - initialTouchY1;
rect1.y += deltaY * 2;
initialTouchY1 = event.tfinger.y;
}
else if (event.tfinger.fingerId == 1) // Second finger
{
int deltaY = event.tfinger.y - initialTouchY2;
rect2.y += deltaY * 2;
initialTouchY2 = event.tfinger.y;
}
break;
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
if (rect1.y < 0)
{
rect1.y = 0;
}
if (rect1.y + rect1.h > h)
{
rect1.y = h - rect1.h;
}
if (rect2.y < 0)
{
rect2.y = 0;
}
if (rect2.y + rect2.h > h)
{
rect2.y = h - rect2.h;
}
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &rect1);
SDL_RenderFillRect(renderer, &rect2);
SDL_RenderPresent(renderer);
}
return 0;
}
But i don’t know what i’m doing wrong. This doesn’t work. This works fine if i implement this using the mousebutton events. But that way i cannot address two finger clicks at the same time. So, what’s wrong with the program?