Android游戏开发教程:手教你写跳跃类游戏
- package jumpball.game;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.DisplayMetrics;
- import android.view.Window;
- import android.view.WindowManager;
- public class GameActivity extends Activity {
- GameView mView;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置无标题
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏模式
- //获取系统的屏幕属性
- DisplayMetrics dm = new DisplayMetrics();
- getWindowManager().getDefaultDisplay().getMetrics(dm);
- mView = new GameView(this, dm.widthPixels, dm.heightPixels);
- //应用这个布局
- setContentView(mView);
- }
- }
- GameView.java
- package jumpball.game;
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.view.SurfaceHolder;
- import android.view.SurfaceView;
- import android.view.SurfaceHolder.Callback;
- //本身就是一个Runnable接口
- public class GameView extends SurfaceView implements Callback, Runnable {
- public int width, height;
- private Canvas mCanvas;
- //刷新界面线程
- private Thread mThread;
- //处理者
- private SurfaceHolder mSurfaceHolder;
- private boolean mIsRunning = false;
- private int TIME_IN_FRAME = 50;
- GameActivity gameActivity;
- public GameView(Context context, int width, int height) {
- super(context);
- //setFocusable(true);
- //activity是 context的一个子类。
- gameActivity = (GameActivity) context;
- this.width = width;
- this.height = height;
- mSurfaceHolder = getHolder();
- mSurfaceHolder.addCallback(this);
- }
- public void mDraw() {
- //设置画布的颜色
- mCanvas.drawColor(Color.WHITE);
- drawBG(mCanvas);
- }
- public void drawBG(Canvas mCanvas) {
- Paint mPaint = new Paint();
- mPaint.setColor(Color.BLACK);
- //设置透明度
- mPaint.setAlpha(50);
- //设置抗锯齿
- mPaint.setAntiAlias(true);
- float h = height * 0.01666667f;
- for (int i = 0; i < height; i += h) {
- mCanvas.drawLine(0, i, width, i, mPaint);
- }
- }
- public void surfaceChanged(SurfaceHolder holder, int format, int width,
- int height) {
- }
- public void surfaceCreated(SurfaceHolder holder) {
- mIsRunning = true;
- //新建一个刷屏线程
- mThread = new Thread(this);
- mThread.start();
- }
- public void surfaceDestroyed(SurfaceHolder holder) {
- //销毁这个,
- mIsRunning=false;
- }
- public void run() {
- //决定线程是否继续执行
- while (mIsRunning) {
- long startTime = System.currentTimeMillis();
- //调用mDraw进行绘制
- synchronized (mSurfaceHolder) {
- mCanvas = mSurfaceHolder.lockCanvas();
- mDraw();
- mSurfaceHolder.unlockCanvasAndPost(mCanvas);
- }
- long endTime = System.currentTimeMillis();
- int diffTime = (int) (endTime - startTime);
- while (diffTime < TIME_IN_FRAME) {
- diffTime = (int) (System.currentTimeMillis() - startTime);
- Thread.yield();
- }
- }
- }
- }
- 游戏介绍:这次编写的游戏是一款跳跃类游戏,类似与涂鸦跳跃。我们通过小球触碰方块,完成小球的跳跃。我们将在这一列的博客中来实现这款游戏的开发。
- 小小游戏,只供娱乐!!!