My program in C is not working correctly. I am using Mac OS.
My program was made to move the square with the WASD keys, but the executable does not open when compiled.
Here is my code:
#include <stdio.h>
#include "raylib.h"
#define SW 800
#define SH 800
int main() {
int posX = 0;
int posY = 0;
char posX2;
char posY2;
InitWindow(SW, SH, "Window");
while (!WindowShouldClose()) {
scanf("%c", &posX2);
scanf("%c", &posY2);
switch (posX2) {
case 'a':
posX--;
break;
case 'd':
posX++;
break;
}
switch (posY2) {
case 'w':
posY--;
break;
case 's':
posY++;
break;
}
BeginDrawing();
ClearBackground(RAYWHITE);
DrawRectangle(posX, posY, 100, 100, RED);
EndDrawing();
}
CloseWindow();
return 0;
}
Is this an OS problem or a Raylib problem?
scanf()
is inappropriate to read keyboard input because of standard stream buffering and the terminal line discipline. Thankfully raylib takes provides a portable and powerful alternative to read the keyboard state: you can use IsKeyDown()
with a symbol for the key, such as KEY_A
for alphanumeric keys and KEY_LEFT
... for cursor movement keys. Look at the documentation for more information and examples.
Here is a modified version:
#include <stdio.h>
#include <raylib.h>
#define SW 800
#define SH 800
int main(void) {
int posX = 0;
int posY = 0;
InitWindow(SW, SH, "Window");
while (!WindowShouldClose()) {
if (IsKeyDown(KEY_A)) posX--;
if (IsKeyDown(KEY_D)) posX++;
if (IsKeyDown(KEY_W)) posY--;
if (IsKeyDown(KEY_S)) posY++;
BeginDrawing();
ClearBackground(RAYWHITE);
DrawRectangle(posX, posY, 100, 100, RED);
EndDrawing();
}
CloseWindow();
return 0;
}