用SurfaceView實現Android遊戲搖桿

這段時間研究自定義控件,遂想起遊戲裏的搖桿的實現挺有意思,因而來本身寫一套熟悉熟悉,關於SurfaceView的特性網上也有不少,故不贅述,反正繪圖用起來挺爽就是了,永遠的告別了JAVA GUI手動實現雙緩衝的時代了……android

 

 

import com.game.graphics.utils.MathUtils;
 
 import android.content.Context;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.Paint;
 import android.graphics.PixelFormat;
 import android.graphics.Point;
 import android.graphics.PorterDuff.Mode;
 import android.util.AttributeSet;
 import android.view.MotionEvent;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.SurfaceHolder.Callback;
 
 public class Rudder extends SurfaceView implements Runnable,Callback{
 
     private SurfaceHolder mHolder;
     private boolean isStop = false;
     private Thread mThread;
     private Paint  mPaint;
     private Point  mRockerPosition; //搖桿位置
     private Point  mCtrlPoint = new Point(80,80);//搖桿起始位置
     private int    mRudderRadius = 20;//搖桿半徑
     private int    mWheelRadius = 60;//搖桿活動範圍半徑
     private RudderListener listener = null; //事件回調接口
     public static final int ACTION_RUDDER = 1 , ACTION_ATTACK = 2; // 1:搖桿事件 2:按鈕事件(未實現)
    
     public Rudder(Context context) {
         super(context);
     }
    
     public Rudder(Context context, AttributeSet as) {
         super(context, as);
         this.setKeepScreenOn(true);
         mHolder = getHolder();
         mHolder.addCallback(this);
         mThread = new Thread(this);
         mPaint = new Paint();
         mPaint.setColor(Color.GREEN);
         mPaint.setAntiAlias(true);//抗鋸齒
         mRockerPosition = new Point(mCtrlPoint);
         setFocusable(true);
         setFocusableInTouchMode(true);
         setZOrderOnTop(true);
         mHolder.setFormat(PixelFormat.TRANSPARENT);//設置背景透明
     }
    
     //設置回調接口
     public void setRudderListener(RudderListener rockerListener) {
         listener = rockerListener;
     }
 
     @Override
     public void run() {
         Canvas canvas = null;
         while(!isStop) {
             try {
                 canvas = mHolder.lockCanvas();
                 canvas.drawColor(Color.TRANSPARENT,Mode.CLEAR);//清除屏幕
                 mPaint.setColor(Color.CYAN);
                 canvas.drawCircle(mCtrlPoint.x, mCtrlPoint.y, mWheelRadius, mPaint);//繪製範圍
                 mPaint.setColor(Color.RED);
                 canvas.drawCircle(mRockerPosition.x, mRockerPosition.y, mRudderRadius, mPaint);//繪製搖桿
             } catch (Exception e) {
                 e.printStackTrace();
             } finally {
                 if(canvas != null) {
                     mHolder.unlockCanvasAndPost(canvas);
                 }
             }
             try {
                 Thread.sleep(30);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     }
    
     @Override
     public void surfaceChanged(SurfaceHolder holder, int format, int width,
             int height) {
        
     }
 
     @Override
     public void surfaceCreated(SurfaceHolder holder) {
         mThread.start();
     }
 
     @Override
     public void surfaceDestroyed(SurfaceHolder holder) {
         isStop = true;
     }
    
     @Override
     public boolean onTouchEvent(MotionEvent event) {
         int len = MathUtils.getLength(mCtrlPoint.x, mCtrlPoint.y, event.getX(), event.getY());
         if(event.getAction() == MotionEvent.ACTION_DOWN) {
             //若是屏幕接觸點不在搖桿揮動範圍內,則不處理
             if(len >mWheelRadius) {
                 return true;
             }
         }
         if(event.getAction() == MotionEvent.ACTION_MOVE){
             if(len <= mWheelRadius) {
                 //若是手指在搖桿活動範圍內,則搖桿處於手指觸摸位置
                 mRockerPosition.set((int)event.getX(), (int)event.getY());
                
             }else{
                 //設置搖桿位置,使其處於手指觸摸方向的 搖桿活動範圍邊緣
                 mRockerPosition = MathUtils.getBorderPoint(mCtrlPoint, new Point((int)event.getX(), (int)event.getY()), mWheelRadius);
             }
             if(listener != null) {
                 float radian = MathUtils.getRadian(mCtrlPoint, new Point((int)event.getX(), (int)event.getY()));
                 listener.onSteeringWheelChanged(ACTION_RUDDER,Rudder.this.getAngleCouvert(radian));
             }
         }
         //若是手指離開屏幕,則搖桿返回初始位置
         if(event.getAction() == MotionEvent.ACTION_UP) {
             mRockerPosition = new Point(mCtrlPoint);
         }
         return true;
     }
    
     //獲取搖桿偏移角度 0-360°
     private int getAngleCouvert(float radian) {
         int tmp = (int)Math.round(radian/Math.PI*180);
         if(tmp < 0) {
             return -tmp;
         }else{
             return 180 + (180 - tmp);
         }
     }
    
     //回調接口
     public interface RudderListener {
         void onSteeringWheelChanged(int action,int angle);
     }
 }canvas

import android.graphics.Point;
 
 public class MathUtils {
     //獲取兩點間直線距離
     public static int getLength(float x1,float y1,float x2,float y2) {
         return (int)Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));
     }
     /**
      * 獲取線段上某個點的座標,長度爲a.x - cutRadius
      * @param a 點A
      * @param b 點B
      * @param cutRadius 截斷距離
      * @return 截斷點
      */
     public static Point getBorderPoint(Point a, Point b,int cutRadius) {
         float radian = getRadian(a, b);
         return new Point(a.x + (int)(cutRadius * Math.cos(radian)), a.x + (int)(cutRadius * Math.sin(radian)));
     }
    
     //獲取水平線夾角弧度
     public static float getRadian (Point a, Point b) {
         float lenA = b.x-a.x;
         float lenB = b.y-a.y;
         float lenC = (float)Math.sqrt(lenA*lenA+lenB*lenB);
         float ang = (float)Math.acos(lenA/lenC);
         ang = ang * (b.y < a.y ? -1 : 1);
         return ang;
     }
 }ide

 

<?xml version="1.0" encoding="utf-8"?>
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
     <ImageView
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:scaleType="fitXY"
         android:src="@drawable/xx"/>
     <RelativeLayout
         android:id="@+id/ctrls"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">
          <com.game.demo.views.Rudder
             android:id="@+id/rudder"
             android:layout_width="480dip"
             android:layout_height="160dip"
             android:layout_alignParentBottom="true"
             android:layout_centerHorizontal="true"/>
     </RelativeLayout>
 </FrameLayout>this

 

     setContentView(R.layout.main);
         Rudder rudder = (Rudder) findViewById(R.id.rudder);
         rudder.setRudderListener(new RudderListener() {
            
             @Override
             public void onSteeringWheelChanged(int action, int angle) {
                 if(action == Rudder.ACTION_RUDDER) {
                     //TODO:事件實現
                 }
             }
         });orm

相關文章
相關標籤/搜索