-
Notifications
You must be signed in to change notification settings - Fork 0
/
MoveObjects.c
114 lines (93 loc) · 3 KB
/
MoveObjects.c
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
//
// Created by Gabriel Mitterrutzner on 28.04.17.
//
#include <SDL2/SDL.h>
#include <stdbool.h>
int main(int argc, char ** argv){
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Rect playerPos;
int width = 500;
int height = 500;
int step = 5;
playerPos.h = 50;
playerPos.w = 50;
playerPos.x = (width - playerPos.h) / 2;
playerPos.y = (width - playerPos.w) / 2;
if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
printf("Error %s", SDL_GetError());
return -1;
}
window = SDL_CreateWindow("Move objects width arrow keys", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN);
if (window == NULL){
printf("Error %s", SDL_GetError());
return -2;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL){
printf("Error %s", SDL_GetError());
return -3;
}
if (SDL_RenderSetLogicalSize(renderer, width, height) == -1){
printf("Error %s", SDL_GetError());
return -4;
}
if (SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255) == -1){
printf("Error %s", SDL_GetError());
return -5;
}
if (SDL_RenderClear(renderer) == -1){
printf("Error %s", SDL_GetError());
return -6;
}
bool loop = true;
while ( loop )
{
SDL_Event event;
while ( SDL_PollEvent( &event ) )
{
if ( event.type == SDL_QUIT )
loop = false;
else if ( event.type == SDL_KEYDOWN )
{
switch ( event.key.keysym.sym )
{
case 'q':
loop = false;
break;
case SDLK_RIGHT:
playerPos.x += step;
break;
case SDLK_LEFT:
playerPos.x -= step;
break;
// Remeber 0,0 in SDL is left-top. So when the user pressus down, the y need to increase
case SDLK_DOWN:
playerPos.y += step;
break;
case SDLK_UP:
playerPos.y -= step;
break;
default :
break;
}
}
}
SDL_RenderClear(renderer);
// Change color to yellow
SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255 );
// Render our "player"
SDL_RenderFillRect(renderer, &playerPos);
SDL_RenderDrawLine(renderer, 0, 0, 500, 500);
SDL_RenderDrawLine(renderer, 500, 0, 0, 500);
// Change color to black
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255 );
// Render the changes above
SDL_RenderPresent(renderer);
// Add a 16msec delay to make our game run at ~60 fps
SDL_Delay( 16 );
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}