FPS游戏
引用:http://www.oschina.net/code/snippet_54100_6233
1 |
private boolean drawall= false ; |
02 |
private RefreshHandler mRedrawHandler = new RefreshHandler(); |
03 |
class RefreshHandler extends Handler { |
04 |
05 |
@Override |
06 |
public void handleMessage(Message msg) { |
07 |
KetrisCanvas. this .update(); |
08 |
KetrisCanvas. this .invalidate(); |
09 |
} |
10 |
11 |
public void sleep( long delayMillis) { |
12 |
this .removeMessages( 0 ); |
13 |
sendMessageDelayed(obtainMessage( 0 ), delayMillis); |
14 |
} |
15 |
}; |
16 |
long mLastMove= 0 ; |
17 |
long mMoveDelay= 30 ; |
18 |
public void update() { |
19 |
long now = System.currentTimeMillis(); |
20 |
21 |
if (now - mLastMove > mMoveDelay) { |
22 |
//gameLogic(); 这里是游戏逻辑 |
23 |
|
24 |
mLastMove = now; |
25 |
} |
26 |
mRedrawHandler.sleep(mMoveDelay); |
27 |
|
28 |
} |
29 |
public void onDraw(Canvas canvas) |
30 |
{ super .onDraw(canvas); |
31 |
this .paint(); //这里是绘制到缓冲屏幕 |
32 |
canvas.drawBitmap(g.offs, 0 , 0 , g.p); |
33 |
} |
[代码] [Java]代码
01 |
public class KetrisCanvas extends SurfaceView implements SurfaceHolder.Callback |
02 |
03 |
{ |
04 |
05 |
在构造方法完成 下面 2 句 |
06 |
holder = this .getHolder(); //获取holder |
07 |
holder.addCallback( this ); |
08 |
09 |
10 |
@Override |
11 |
public void surfaceChanged(SurfaceHolder holder, int format, int width, |
12 |
int height) { |
13 |
// TODO Auto-generated method stub |
14 |
|
15 |
} |
16 |
17 |
Thread t; |
18 |
boolean isrun= true ; |
19 |
final SurfaceHolder holder; |
20 |
@Override |
21 |
public void surfaceCreated(SurfaceHolder holder) { |
22 |
// TODO Auto-generated method stub |
23 |
|
24 |
t= new Thread(){ |
25 |
public void run() |
26 |
{ while (isrun) |
27 |
{ |
28 |
long start=System.currentTimeMillis(); |
29 |
Canvas canvas=KetrisCanvas. this .holder.lockCanvas( null ); |
30 |
//这里完成游戏逻辑 |
31 |
32 |
paint(); //这里是屏幕绘制 |
33 |
canvas.drawBitmap(g.offs, 0 , 0 , null ); |
34 |
|
35 |
KetrisCanvas. this .holder.unlockCanvasAndPost(canvas); |
36 |
long end=System.currentTimeMillis(); |
37 |
if ( 200 >end-start) |
38 |
{ |
39 |
try {Thread.sleep( 200 -(end-start));} catch (Exception e){} |
40 |
} |
41 |
} |
42 |
} |
43 |
}; |
44 |
t.start(); |
45 |
} |
46 |
@Override |
47 |
public void surfaceDestroyed(SurfaceHolder holder) { |
48 |
// TODO Auto-generated method stub |
49 |
if (t!= null ) |
50 |
{ isrun= false ; |
51 |
} |
52 |
} |