This is how I've made the rectangle to move by pressing buttons:
#include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_native_dialog.h>
#include <allegro5/allegro_primitives.h>
#define ScreenWidth 1440
#define ScreenHeight 790
int main()
{
if (!al_init())
{
al_show_native_message_box(NULL, NULL, NULL, "Could not initialize Allegro 5", NULL, NULL);
return -1;
}
al_set_new_display_flags(ALLEGRO_WINDOWED);
ALLEGRO_DISPLAY *display = al_create_display(ScreenWidth, ScreenHeight);
al_set_window_position(display, 0, 0);
al_set_window_title(display, "Lab 14");
if (!display)
{
al_show_native_message_box(display, "Error", NULL, "Display window was not created succesfully", NULL, ALLEGRO_MESSAGEBOX_ERROR);
return -1;
}
al_init_primitives_addon();
al_install_keyboard();
ALLEGRO_COLOR orange = al_map_rgb(255, 160, 0);
ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
al_register_event_source(event_queue, al_get_keyboard_event_source());
bool done = false;
int x = 10, y = 10;
int moveSpeed = 5;
int state = NULL;
while (!done)
{
ALLEGRO_EVENT events;
al_wait_for_event(event_queue, &events);
if(events.type = ALLEGRO_EVENT_KEY_DOWN)
{
switch(events.keyboard.keycode)
{
case ALLEGRO_KEY_DOWN:
y += moveSpeed;
break;
case ALLEGRO_KEY_UP:
y -= moveSpeed;
break;
case ALLEGRO_KEY_RIGHT:
x += moveSpeed;
break;
case ALLEGRO_KEY_LEFT:
x -= moveSpeed;
break;
case ALLEGRO_KEY_ESCAPE:
done = true;
break;
}
}
al_draw_rectangle(x, y, x + 20, y + 20, orange, 2.0);
al_flip_display();
al_clear_to_color(al_map_rgb(0, 0, 0));
}
al_draw_rectangle(300, 600, 500, 200, orange, 2.0);
al_destroy_display(display);
al_destroy_event_queue(event_queue);
return 0;
}
How do I modify the code to make the rectangle smoothly cross the display border while appearing on the opposite side? Smoothly means that it shouldn't fully appear on the opposite side.
You have the screen dimensions and position and size of your rectangle, thus you know how much it will be cut off screen.
You have to check every rectangle before you blit it to the screen.
If you detect a cut simply calculate how much and make another blit call for the same rectangle on displaced coordinates on the other side of the screen so just a part of the rect. is visible.
In your code
al_draw_rectangle(x, y, x + 20, y + 20, orange, 2.0);
add another call with different coordinates if the rectangle is (partially) offscreen.