Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

DragTheBall 小遊戲:Android 拖拽技術實作

本例是一個拖動小球的小遊戲,主要用到 Android 2D 繪圖技術與自訂元件技術。功能雖簡單,卻很適合入門 Touch 事件與自繪。

功能說明

  • 拖動小球後,視窗會顯示當前的 Touch 座標。
  • 選中小球時手機會震動 50ms(需真機才有震動)。
  • 小球會隨手指移動而移動。
  • 加入邊界判斷後,小球不會移出視圖。

實現思路

  1. 自訂一個 BallView 類,用 HashSet<Ball> 存放多個 Ball。
  2. BallView 實作 OnTouchListener 監聽 Touch 事件。
  3. 把 BallView 加入 MainActivity 即可看到效果。

核心程式碼

Ball 實體封裝了座標與圖片資源:

public class Ball {
    public int id;          // 唯一標示
    public float x;         // 橫座標
    public float y;         // 縱座標
    public int drawableId;

    public Ball(float x, float y, int drawableId) {
        this.x = x;
        this.y = y;
        this.drawableId = drawableId;
        id = this.hashCode();
    }
}

在 MainActivity 中建立 BallView、設定背景並加入幾顆小球:

BallView view = new BallView(this);
view.setBackgroundDrawable(getResources().getDrawable(R.drawable.back));
view.addComponent(new Ball(0, 10, R.drawable.ball_blue));
view.addComponent(new Ball(80, 10, R.drawable.bol_geel));
view.addComponent(new Ball(160, 10, R.drawable.bol_groen));
view.addComponent(new Ball(240, 10, R.drawable.bol_rood));
super.onCreate(savedInstanceState);
setContentView(view, new LayoutParams(
    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
Copyright © Linux教程網 All Rights Reserved