C Animation Basics
In this page:
Moving a Shape
The basic animation loop in BGI graphics is: draw a shape, pause briefly, erase that shape, update its position variables, then draw it again at the new location — repeating this cycle rapidly is what creates the illusion of smooth motion on screen.
Example: Moving a Shape
#include <graphics.h>
int main() {
initgraph(0, 0, "");
int x = 0;
for (int i = 0; i < 3; i++) {
circle(x, 100, 10);
delay(100);
cleardevice();
x += 20;
}
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Controlling Speed
delay() pauses program execution for a number of milliseconds you specify, and it's what controls the perceived speed of an animation: a larger delay value between frames makes motion look slower, while a smaller one makes it look faster.
Example: Controlling Speed
#include <graphics.h>
int main() {
initgraph(0, 0, "");
circle(50, 50, 10);
delay(500);
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Preventing Flickering
Calling cleardevice() to erase the whole screen between frames works, but it also causes visible flickering since the entire display blanks out for an instant; erasing only the previous shape by redrawing it in the background color, then drawing the new frame, avoids that flicker.
Example: Preventing Flickering
#include <graphics.h>
int main() {
initgraph(0, 0, "");
int x = 0;
for (int i = 0; i < 3; i++) {
setcolor(BLACK);
circle(x, 100, 10);
x += 10;
setcolor(WHITE);
circle(x, 100, 10);
delay(100);
}
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Bouncing Animations
A bouncing animation tracks a direction variable (such as +1 or -1) alongside a shape's position, and reverses the sign of that direction the moment the shape's coordinates reach a screen boundary, which is what makes it appear to bounce off the edge instead of moving off-screen.
Example: Bouncing Animations
#include <graphics.h>
int main() {
initgraph(0, 0, "");
int x = 0, direction = 1;
for (int i = 0; i < 5; i++) {
if (x >= 100 || x <= 0) {
direction = -direction;
}
x += direction * 10;
delay(50);
}
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Keyframe Based Updates
Animating several shapes together just means updating every shape's position variables once per pass through the same loop, before redrawing all of them, which keeps their movements synchronized to the same timing rather than each shape running on its own independent loop.
Example: Keyframe Based Updates
#include <graphics.h>
int main() {
initgraph(0, 0, "");
int x1 = 0, x2 = 200;
for (int i = 0; i < 3; i++) {
circle(x1, 100, 10);
circle(x2, 100, 10);
x1 += 10;
x2 -= 10;
delay(100);
}
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: