Mobile Gameand Application withJ2ME - Collision Detection
J2ME Game Concept
1. Mobile Game
and Application with
J2ME
อ.เจนโชค เตชะโกเมนท์ (เจ)
jenchoke@hotmail.com
สาขาวิชาสื่อนฤมิต
คณะวิทยาการสารสนเทศ
มหาวิทยาลัยมหาสารคาม
http://www.it.msu.ac.th/nmd
3. การทำางานของ
TimerTask
Main Time Task Display
ควบคุม TimerTask.run ทำาหน้าที่ Paint
Time.schedule()
(display) ตามคำาสั่ง random line
มีวิธีการเขียน code j2me แบบง่ายดังนี้
ครับ โดยเริ่มเขียนจาก
Java Class Java Class J2ME Midlet
extends Canvas extends TimerTask Class
6. import javax.microedition.midlet.*; TimerDemo.java
import javax.microedition.lcdui.*;
import java.util.*;
public class TimerDemo extends MIDlet {
Display display;
StarField field = new StarField();
FieldMover mover = new FieldMover();
Timer timer = new Timer();
public TimerDemo() {
display = Display.getDisplay( this );
}
protected void destroyApp( boolean unconditional ) { }
protected void startApp() {
display.setCurrent( field );
timer.schedule( mover, 0, 50 );
}
protected void pauseApp() { }
public void exit(){
timer.cancel(); // stop scrolling
destroyApp( true );
notifyDestroyed();
}
7. class FieldMover extends TimerTask { TimerDemo.java
public void run() {
field.scroll();
}
}
class StarField extends Canvas {
int height; int width; int[] stars;
Random generator = new Random();
boolean painting = false;
private Random genColor = new Random();
public StarField(){
height = getHeight();
width = getWidth();
stars = new int[ height ];
for( int i = 0; i < height; ++i ){
stars[i] = -1;
}
}
8. public void scroll() {
if( painting ) return; TimerDemo.java
for( int i = height-1; i > 0; --i ){
stars[i] = stars[i-1];
}
stars[0] = ( generator.nextInt() % ( 3 * width ) ) / 2;
if( stars[0] >= width ){
stars[0] = -1;
}
repaint();
}
protected void paint( Graphics g ){
painting = true;
g.setColor( 0, 0, 0 );
g.fillRect( 0, 0, width, height );
for( int y = 0; y < height; ++y ){
int r_color = genColor.nextInt(255);
int g_color = genColor.nextInt(255);
int b_color = genColor.nextInt(255);
g.setColor( r_color, g_color, b_color );
int x = stars[y];
if( x == -1 ) continue;
g.drawLine( x, y, x, y + 1);
}
painting = false;
}