用几天的时间我研究了一下android的框架,android是这么样开发2D游戏的。
我们先来讲GameCanvas(游戏画布) 。这是一个类,你可以这样理解它-----我们游戏的画布。开发游戏的时候大部分的工作都会在这里面完成的 。那么在android 里面 怎样构成我们的GameCanvas。这里我用了
SurfaceView 类,使用这个类的原因是它比较适合游戏画布。然后我们再继承SurfaceHolder.Callback 这个接口
这样我们的GameCanvas类要实现其几个方法:
- public void surfaceCreated(SurfaceHolder holder) {}
- public void surfaceDestroyed(SurfaceHolder holder) {}
- public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
我们在surfaceCreated 方法里面初始化游戏,在surfaceChanged 处理一下当手机碰到外界情况的事件,
surfaceDestroyed 方法里面我们写释放资源等。
这样每个方法里面都会有个参数 SurfaceHolder 这个是什么呢??暂且先不讨论它,后面你会明白他有什么用了,
声明一个SurfaceHolder handle对象,然后在surfaceCreated()方法里面初始化它 如下:handle = this.getHolder();
handle.addCallback(this);
那在哪里绘制我们的游戏画布呢?讲到关键的地方了,这里我们重载view 的 public void draw(Canvas canvas){}方法,
我们就在这个方法里面绘制我们的游戏。
01 | public class GameCanvas extends SurfaceView implements SurfaceHolder.Callback |
02 | { |
03 | private SurfaceHolder handle = null ; |
04 |
05 | private int width = 0 ; |
06 |
07 | private int height = 0 ; |
08 |
09 | public GameCanvas(){ |
10 |
11 | handle = this .getHolder(); |
12 | handle.addCallback( this ); |
13 |
14 | } |
15 |
16 | public void initGame(){ |
17 |
18 | width = this .getWidth(); |
19 | height = this .getHeight(); |
20 | { |
21 |
22 | public void gameLogic(){ |
23 |
24 |
25 | } |
26 |
27 | public void gameInput(){ |
28 |
29 | } |
30 |
31 | @Override |
32 | public void draw(Canvas canvas){ |
33 |
34 | Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); |
35 | paint.setColor(Colcor.Black); |
36 |
37 | canvas.drawRect( new Rect( int startX, int StartY, int endX, int endY)); //此处的Rect跟java里面的有点区别 |
38 | //,不过差不多 自己写坐标就行 0,0,320,440 |
39 |
40 | //上面的语句是将屏幕绘制成黑色 |
41 |
42 | paint.setColor(Cloor.red); |
43 | canvas.drawText( "Andoid GameCanvas" , 100 , 100 ,paint); |
44 |
45 | // |
46 | } |
47 |
48 | // |
49 | @Override |
50 | public void surfaceCreated(SurfaceHolder holder) { |
51 |
52 | this . initGame(); |
53 | new Thread( this ){ |
54 | public void run(){ |
55 |
56 | while ( true ) |
57 | { |
58 | long start=System.currentTimeMillis(); |
59 | Canvas canvas = GameCanvas. this .handle.lockCanvas( null ); |
60 | //logic |
61 | this .draw(canvas); |
62 | canvas.save(); |
63 | //input() |
64 | GameCanvas. this .handle.unlockCanvasAndPost(canvas); |
65 | long end=System.currentTimeMillis(); |
66 | if ( 100 >end-start){ |
67 | try {Thread.sleep( 100 -(end-start));} catch (Exception e){} |
68 | } |
69 | } |
70 | } |
71 | }.start(); |
72 |
73 | } |
74 | @Override |
75 | public void surfaceDestroyed(SurfaceHolder holder) { |
76 |
77 | } |
78 | @Override |
79 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){ |
80 |
81 | } |
82 |
83 | } |