Game animation is often required during the development process of the j2_based program, such as simple text flashing and complex game interface changes. The following describes the principle of animation and the implementation code.
Animation is an illusion realized by taking advantage of the physiological characteristics of human vision temporarily. The following code is constantly changing the content to achieve text flashing.
Program logic: the content to be drawn is changed every 0.2 seconds. If no text is drawn on the screen, it is drawn. Otherwise, the text is drawn.
The implementation code is as follows:
Package welcomecanvas;
Import javax. microedition. lcdui .*;
Public class DongHuaCanvas extends Canvas implements Runnable {
// Indicates whether to draw a string
Boolean B = true;
Public DongHuaCanvas (){
// Start the thread
Thread t = new Thread (this );
T. start ();
}
Protected void paint (Graphics g ){
// Clear screen
G. setColor (255,255,255 );
G. fillRect (0, 0, getWidth (), getHeight ());
G. setColor (0, 0, 0 );
// Draw a string based on the flag variable
If (B = true ){
G. drawString ("blinking text", 50, 50, Graphics. LEFT | Graphics. TOP );
}
}
/**
* The thread method changes the flag variable every 0.2 seconds and re-draws the string.
*/
Public void run (){
While (true ){
// Wait 0.2 seconds
Try {
Thread. sleep (200 );
} Catch (Exception e ){}
// Change the flag variable
B =! B;
// Redraw
Repaint ();
}
}
}
Compared with the program, complicated animations only make different pictures each time and make the actions in the thread more complex.