目标:实现一个小圆随着手在屏幕上面的移动而移动,热门打飞机游戏中自己飞机的操作模式。
/**
* 1.在初始化的时候,绘制初始的实心圆。
* 2.在onTouch方法中实例动画线程并进行启动。
* 3.在线程对象的run方法中根据当前touch位置不断调用drawCircle()方法。
* @author YH
*
*/
public class GameSurfaceView extends SurfaceView implements SurfaceHolder.Callback,OnTouchListene{
public float x;
public float y;
private SurfaceHolder surfaceHolder;
public GameSurfaceView(Context context) {
super(context);
setOnTouchListener(this);
//实例化surfaceHolder
surfaceHolder = this.getHolder();
//添加回调函数
surfaceHolder.addCallback(this);
this.setFocusable(false);
}
//SurfaceView的大小发生变化时被触发。
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
//SurfaceView对象被创建时被触发。
@Override
public void surfaceCreated(SurfaceHolder arg0) {
//绘制初始化时的实心圆
drawCircle();
}
//SurfaceView对象被销毁时被触发。
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
AnimThread animThread = new AnimThread(arg1.getX(), arg1.getY());
Thread thread = new Thread(animThread);
thread.start();
return false;
}
private void drawCircle() {
// TODO Auto-generated method stub
if(surfaceHolder == null){
return;
}
//获得Canvas对象
Canvas canvas = surfaceHolder.lockCanvas();
//清空屏幕
canvas.drawColor(Color.BLACK);
if(canvas == null)
return;
Paint paint = new Paint();
paint.setColor(Color.WHITE);
canvas.drawCircle(x, y, 20, paint);
//释放canvas对象
surfaceHolder.unlockCanvasAndPost(canvas);
}
class AnimThread implements Runnable
{
private float newX, newY;
public AnimThread(float newX, float newY) {
this.newX = newX;
this.newY = newY;
}
@Override
public void run() {
// TODO Auto-generated method stub
float scale = Math.abs(newY - y)/Math.abs(newX - x);
while(newX != x && newY != y){
//向右移动
if(newX > x){
x += 1;
if(newX < x){
x = newX;
}
}
//向左移动
else if(newX < x){
x -= 1;
if(newX > x){
x = newX;
}
}
//向下移动
if(newY > y){
y += scale;
if(newY < y){
y = newY;
}
}
//向上移动
else if(newY < y){
y -= scale;
if(newY > y){
y = newY;
}
}
try{
drawCircle();
Thread.sleep(50);
}catch(Exception e){
}
}
}
}
}