本文主要是介绍让一个游戏人物动起来,,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
2012-04-28 12:13 480人阅读 评论(2) 收藏 举报 游戏 dst thread class null
今天我来复习一下如何让一个游戏人物动起来,下面我发一张截图上来
1、首先,我们要找到一张原图,它的宽度为60*5,高度为57
2、创建一个gameView类
- package com.mwf.move;
- import java.io.IOException;
- import java.io.InputStream;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Canvas;
- import android.graphics.Paint;
- import android.graphics.Rect;
- import android.view.View;
- public class gameView extends View implements Runnable
- {
- // 创建一个线程对象
- public Thread currentThread;
- // 得到图片的对象
- public Bitmap yingwu;
- /**
- * 图片的初始化
- *
- * @param context
- */
- public gameView(Context context)
- {
- super(context);
- // 导入图片资源
- try
- {
- // 注意这里取得图片是在assets文件夹下
- InputStream is = context.getAssets().open("bird03_yingwu.png");
- yingwu = BitmapFactory.decodeStream(is);
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- // 开启线程,十分重要
- startThread();
- }
- // 处理每一帧的播放
- public int index = 0;
- // 人物的x和y坐标
- int x = 700;
- int y = 200;
- // src是原图片,dst是绘制在屏幕上的图片
- public Rect src = new Rect();
- public Rect dst = new Rect();
- /**
- * 图片的绘制
- */
- protected void onDraw(Canvas canvas)
- {
- super.onDraw(canvas);
- // 创建一个Paint的实例
- Paint paint = new Paint();
- // 首先取得人物的第一帧
- src.left = index * 60;
- src.right = src.left + 60;
- src.top = 0;
- src.bottom = 57;
- dst.left = x;
- dst.right = dst.left + 60;
- dst.top = y;
- dst.bottom = dst.top + 57;
- canvas.drawBitmap(yingwu, src, dst, paint);
- // 帧数的累加
- index++;
- // 总共5帧
- index %= 5;
- // 人物的移动
- x -= 3;
- }
- /**
- * 开启线程
- */
- public void startThread()
- {
- currentThread = new Thread(this);
- currentThread.start();
- }
- /**
- * 关闭线程
- */
- public void stopThread()
- {
- currentThread = null;
- }
- /**
- * 实现线程的方法
- */
- public void run()
- {
- while (currentThread != null)
- {
- //实现界面刷新
- this.postInvalidate();
- try
- {
- Thread.sleep(200);
- } catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- }
- }
- package com.mwf.move;
- import android.app.Activity;
- import android.os.Bundle;
- public class MoveBitmapActivity extends Activity
- {
- public gameView gameview;
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(gameview = new gameView(this));
- }
这篇关于让一个游戏人物动起来,的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!