SurfaceView(2D游戏基础)

目标:实现一个小圆随着手在屏幕上面的移动而移动,热门打飞机游戏中自己飞机的操作模式。

/**
 * 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){
     
    }
   }
  }
  
 }

 

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值