美文网首页
安卓版传感器利用之带体感操作的打砖块小游戏

安卓版传感器利用之带体感操作的打砖块小游戏

作者: Jane_ad7e | 来源:发表于2017-06-08 15:20 被阅读0次

    创建一个名为HitBall-master的项目

    Ball类:主要是进行打向砖块的球进行的绘制,以及最开始的位置的定义

    部分代码如下:

    //发射坐标
    public void shot(int x, int y) {
    mSpeed.x = x;
    mSpeed.y = y;
    }

    //绘制圆
    public void draw(Canvas canvas) {
    canvas.drawCircle(mCenter.x, mCenter.y, mRadius, mPaint);
    mCenter.offset(mSpeed.x, mSpeed.y);
    }

    //设置绘制位置
    public void setPosition(int x, int y) {
    mCenter.x = x;
    mCenter.y = y;
    }
    public Bat() {
    mPaint = new Paint();
    mPaint.setColor(Color.MAGENTA);
    mSpeed = DEFAULT_SPEED;
    mWidth = DEFAULT_WIDTH;
    }

    //左移
    public void moveLeft() {
    mBody.offset(-mSpeed, 0);
    }
    //右移
    public void moveRight() {
    mBody.offset(mSpeed, 0);
    }
    //绘制板
    public void draw(Canvas canvas) {
    canvas.drawRect(mBody, mPaint);
    }
    //设置位置
    public void setBodyPosition(Rect body) {
    mBody = body;
    }

    Brick类:绘制砖块,实现砖块的颜色随机变化,以及砖块的生命周期:碰撞后颜色改变,以及最终 的消失

    部分代码如下:


    //砖块颜色
    private static int[] sBloodColors = {
    Color.RED, Color.YELLOW, Color.GREEN
    };

    //定义砖块
    public Brick(int row, int col, int width, int height, int blood) {
    int left = col * width + BRICK_GAP / 2;
    int right = left + width - 3 * BRICK_GAP / 2;
    int top = row * height + BRICK_GAP;
    int bottom = top + height - BRICK_GAP;
    mBody = new Rect(left, top, right, bottom);
    mBlood = blood;
    this.row = row;
    this.col = col;
    }

    //砖块绘制
    @Override
    public void draw(Canvas canvas) {
    mPaint.setColor(sBloodColors[mBlood]);
    mPaint.setStyle(Paint.Style.FILL);
    canvas.drawRect(mBody, mPaint);
    mPaint.setColor(Color.BLACK);
    mPaint.setStyle(Paint.Style.STROKE);
    canvas.drawRect(mBody.left + BRICK_BORDER,
    mBody.top + BRICK_BORDER,
    mBody.right - BRICK_BORDER,
    mBody.bottom - BRICK_BORDER,
    mPaint);
    }

    //判断砖块数(碰撞则减一)
    @Override
    public boolean hit() {
    mBlood--;
    return mBlood < 0;
    }

    Table类:判断砖块打击的位置以及应该做出的相应反应,添加了背景音乐,

    部分代码如下

    //音乐加载
    private void loadSound(Context context) {
    mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
    mAssetManager = context.getAssets();
    try {
    String[] filenames = mAssetManager.list("sounds");
    for (String filename : filenames) {
    AssetFileDescriptor fd = mAssetManager.openFd("sounds/" + filename);
    int soundId = mSoundPool.load(fd, 0);
    mSounds.add(soundId);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    //更新关卡
    private void loadLevel() {
    //初始化数组,20行,5列
    mCells = new Cell[ROW_NUM][COL_NUM];
    mCellWidth = mBoundary.width() / COL_NUM;
    mCellHeight = mBoundary.height() / ROW_NUM;
    try {
    String[] filenames = mAssetManager.list("levels");
    // TODO: 应该根据关卡加载
    String filename = filenames[0];
    loadLevel(filename);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    private void loadLevel(String filename) {
    try {
    InputStream inputStream = mAssetManager.open("levels/" + filename);
    BufferedReader reader =
    new BufferedReader(new InputStreamReader(inputStream));
    String line;
    int row = 0;
    Paint paint = new Paint();
    while ((line = reader.readLine()) != null) {
    String[] cells = line.split(",");
    for (int col = 0; col < cells.length; col++) {
    String cell = cells[col];
    if (cell.equals("x")) {
    int blood = (int) (Math.floor(Math.random() * 3));
    //绘制砖块
    Cell brick = new Brick(row, col, mCellWidth, mCellHeight, blood);
    brick.setPaint(paint);
    mCells[row][col] = brick;
    }
    }
    row++;
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    //设置球体
    public void setBall(Ball ball) {
    mBall = ball;
    mBall.setRadius(mBoundary.width() / 20);
    }
    //设置球板
    public void setBat(Bat bat) {
    mBat = bat;
    mBat.setWidth(mBoundary.width() / 3);
    }

    public void showGameOver() {
    mShowGameOver = true;
    mBall.stop();
    }

    public void showGamePass() {
    mShowGamePass = true;
    mBall.stop();
    }

    public void draw(Canvas canvas) {
    canvas.drawColor(Color.LTGRAY);
    if (mShowGameOver) {
    canvas.drawText("Game Over!", mBoundary.centerX() - 218, mBoundary.centerY(), mPaintGameOver);
    } else if (mShowGamePass) {
    canvas.drawText("过关了!", mBoundary.centerX() - 168, mBoundary.centerY(), mPaintGameOver);
    }
    // 绘制边界
    canvas.drawPath(mBoundaryPath, mPaintBoundary);

    // 绘制砖块
    for (int row = 0; row < ROW_NUM; row++) {
    for (int col = 0; col < COL_NUM; col++) {
    Cell cell = mCells[row][col];
    if (cell != null) {
    cell.draw(canvas);
    }
    }
    }

    // 判断球是否和边界碰撞(碰撞则改变移动的x.y为相反值)
    int hitType = getHitType();
    if ((hitType & (HIT_TOP | HIT_BOTTOM)) > 0) {
    mBall.reverseYSpeed();
    }
    if ((hitType & (HIT_LEFT | HIT_RIGHT)) > 0) {
    mBall.reverseXSpeed();
    }
    if (isBatHit() && mBall.isToBottom()) {
    mBall.reverseYSpeed();
    }
    mBall.draw(canvas);

    moveBat();
    mBat.draw(canvas);
    }

    //是否球与板是否碰撞
    private boolean isBatHit() {
    Point c = mBall.getCenter();
    float r = mBall.getRadius();
    Rect batBody = mBat.getBody();
    if (c.x >= batBody.left && c.x <= batBody.right) {
    if (c.y - r < batBody.bottom && c.y + r > batBody.top) {
    return true;
    }
    }
    return false;
    }

    //获取球与球板的碰撞类型
    private int getHitType() {
    int type = HIT_NONE;
    Point c = mBall.getCenter();
    float r = mBall.getRadius();
    int row = c.y / mCellHeight;
    int col = c.x / mCellWidth;
    Cell cell = null;
    boolean hitCell = false;
    Rect body = null;
    boolean ballInTable = mBoundary.contains(c.x, c.y);
    // 判断撞头
    if (ballInTable && row > 0) {
    cell = mCells[row - 1][col];
    if (cell != null) {
    body = cell.getBody();
    hitCell = c.y > body.bottom && c.y - r <= body.bottom;
    if (hitCell) {
    playHitBrickSound(cell);
    if (cell.hit()) {
    mCells[cell.row][cell.col] = null;
    }
    }
    }
    }
    if (mBall.isToTop() && (c.y - r <= 0 || hitCell)) {
    type |= HIT_TOP;
    }
    // 判断撞右边
    hitCell = false;
    if (ballInTable && col < COL_NUM - 1) {
    cell = mCells[row][col + 1];
    if (cell != null) {
    body = cell.getBody();
    hitCell = c.x < body.left && c.x + r >= body.left;
    if (hitCell) {
    playHitBrickSound(cell);
    if (cell.hit()) {
    mCells[cell.row][cell.col] = null;
    }
    }
    }
    }
    if (mBall.isToRight() &&
    (c.x + r >= mBoundary.right && c.y < mBoundary.bottom || hitCell)) {
    type |= HIT_RIGHT;
    }
    // 判断撞左边
    hitCell = false;
    if (ballInTable && col > 0) {
    cell = mCells[row][col - 1];
    if (cell != null) {
    body = cell.getBody();
    hitCell = c.x > body.right && c.x - r <= body.right;
    if (hitCell) {
    playHitBrickSound(cell);
    if (cell.hit()) {
    mCells[cell.row][cell.col] = null;
    }
    }
    }
    }
    if (mBall.isToLeft() &&
    ((c.x - r <= 0 && c.y < mBoundary.bottom) || hitCell)) {
    type |= HIT_LEFT;
    }
    // 判断撞下边
    if (ballInTable && row < ROW_NUM - 1) {
    cell = mCells[row + 1][col];
    if (cell != null) {
    body = cell.getBody();
    hitCell = c.y < body.top && c.y + r >= body.top;
    if (hitCell) {
    playHitBrickSound(cell);
    if (cell.hit()) {
    mCells[cell.row][cell.col] = null;
    }
    }
    }
    }
    if (mBall.isToBottom() && hitCell) {
    type |= HIT_BOTTOM;
    }
    return type;
    }

    //设置碰撞音乐
    private void playHitBrickSound(Cell cell) {
    mSoundPool.play(mSounds.get(cell.getBlood()), 1f, 1f, 0, 0, 1);
    }

    // 移动板
    public void moveBat() {
    if (isBatMoving) {
    if (isBatMoveToLeft) {
    // 板左移动
    if (mBat.getBody().left > mBoundary.left) mBat.moveLeft();
    } else {
    // 板右移动
    if (mBat.getBody().right < mBoundary.right) mBat.moveRight();
    }
    }
    }

    //通过触摸事件移动板
    public void startBatMove(MotionEvent e) {
    if (mBoundary.contains((int) e.getX(), (int) e.getY())) {
    isBatMoving = true;
    if (e.getX() > mBoundary.centerX()) { // move right
    if (mBat.getBody().right < mBoundary.right) isBatMoveToLeft = false;
    } else {
    if (mBat.getBody().left > mBoundary.left) isBatMoveToLeft = true;
    }
    }
    }


    public void startBatMove(double roll) {
    if (isBatMoving) {
    if (isBatMoveToLeft) {
    if (roll < 8 && roll > -10) {
    isBatMoving = false;
    } else if (roll <= -10) {
    isBatMoveToLeft = true;
    }
    } else {
    if (roll > -8 && roll < 10) {
    isBatMoving = false;
    } else if (roll >= 10) {
    isBatMoveToLeft = false;
    }
    }
    } else {
    if (roll <= -10) {
    isBatMoving = true;
    isBatMoveToLeft = true;
    } else if (roll >= 10) {
    isBatMoving = true;
    isBatMoveToLeft = false;
    }
    }
    }

    // 通过倾斜度改变板的形状
    public void changeBatBody(double pitch) {
    Rect body = mBat.getBody();
    boolean wider = body.width() == mBoundary.width(); //板和边界宽度是否一致
    boolean higher = body.height() > mNormalBatBody.height();//板是否比正常板的高度高
    if (wider) {
    if (pitch > -25) {//倾斜度判断
    body.left = mNormalBatBody.left;
    body.right = mNormalBatBody.right;
    }
    } else {
    if (pitch < -30) {
    body.left = mBoundary.left;
    body.right = mBoundary.right;
    }
    }
    if (higher) {
    if (pitch < 10) {
    body.top = mNormalBatBody.top;
    }
    } else {
    if (pitch > 15) {
    body.top = body.bottom - 10 * body.height();
    }
    }
    }

    public void stopBatMove() {
    isBatMoving = false;
    }

    // 重置body和球
    public void reset() {
    int left = mBoundary.centerX() - mBat.getWidth() / 2;
    int top = mBoundary.bottom - Bat.DEFAULT_HEIGHT;
    int right = mBoundary.centerX() + mBat.getWidth() / 2;
    int bottom = mBoundary.bottom;
    // 绘制body
    Rect body = new Rect(left, top, right, bottom);
    mNormalBatBody = new Rect(body);
    // 设置body位置
    mBat.setBodyPosition(body);
    // 设置球位置
    mBall.setPosition(mBoundary.centerX(), (int) (top - mBall.getRadius()));
    mBall.stop();
    loadLevel();
    mShowGameOver = false;
    mShowGamePass = false;
    }

    //射击球
    public void shotBall() {
    mBall.shot(20, -20);
    }

    //是否球出界
    public boolean isBallOutside() {
    Point c = mBall.getCenter();
    return c.y - 100 > mBoundary.bottom;
    }

    // 是否还有砖块
    public boolean hasNoneBrick() {
    for (int row = 0; row < ROW_NUM; row++) {
    for (int col = 0; col < COL_NUM; col++) {
    Cell cell = mCells[row][col];
    if (cell instanceof Brick) {
    return false;
    }
    }
    }
    return true;
    }
    }

    GameView类:利用安卓的传感器操作随着手机的倾斜角度实现打砖块的带体感操作

    部分代码如下:

    /**
    * 第一步:获得传感器管理器
    * 第二步:为具体的传感器注册监听器
    * 第三步:实现具体的监听方法
    * public void onSensorChanged(SensorEvent event) {}
    public void onAccuracyChanged(Sensor sensor ,int accuracy ){}
    */

    public class GameView extends SurfaceView implements Runnable, SurfaceHolder.Callback,
    SensorEventListener {
    //游戏状态常量
    public static int STATE_READY = 1;
    public static int STATE_PLAY = 2;
    public static int STATE_PASS = 3;
    public static int STATE_OVER = 4;

    private int mState;

    private Table mTable;
    private Ball mBall;
    private Bat mBat;

    private boolean mIsRunning;
    private GestureDetector mGestureDetector;
    private SensorManager mSensorManager;

    public GameView(Context context, AttributeSet attrs) {
    super(context, attrs);
    getHolder().addCallback(this);
    //实例化手势识别对象
    mGestureDetector = new GestureDetector(getContext(), new GameGestureDetector());
    //实例化传感器管理对象
    mSensorManager = (SensorManager) context.getSystemService(context.SENSOR_SERVICE);

    //设置旋转向量传感器
    Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
    //监听传感器改变的采样率是否为适合游戏的速率
    boolean ok = mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);

    Log.d("mytag", "ok = " + ok);
    Log.d("mytag", "sensor = " + sensor);

    //实例化窗口管理器
    WindowManager windowManager = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);

    //实例化矩形
    Rect screenRect = new Rect();

    windowManager.getDefaultDisplay().getRectSize(screenRect);

    mTable = new Table(context, screenRect);
    mBall = new Ball();
    mTable.setBall(mBall);
    mBat = new Bat();
    mTable.setBat(mBat);
    mTable.reset();
    mState = STATE_READY;
    }

    //判断触摸事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN: //单点触碰
    case MotionEvent.ACTION_MOVE: //触摸点移动动作
    if (mIsRunning && mState == STATE_PLAY) {
    //当状态为STATE_PLAY球开始移动(mIsRunning mState同为1)
    mTable.startBatMove(event);
    }
    break;
    case MotionEvent.ACTION_UP: //单点触摸离开动作
    mTable.stopBatMove();
    break;
    }
    mGestureDetector.onTouchEvent(event);
    return true;
    }

    //监听传感器的值变化
    @Override
    public void onSensorChanged(SensorEvent event) {
    //
    if (!mIsRunning || mState != STATE_PLAY) return;
    int sensorType = event.sensor.getType(); //存储传感器类型
    float[] rotationMatrix;
    switch (sensorType) {
    case Sensor.TYPE_ROTATION_VECTOR: //为旋转矢量传感器(代表设备的方向)
    rotationMatrix = new float[16];
    SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values);
    float[] orientationValues = new float[3];
    SensorManager.getOrientation(rotationMatrix, orientationValues);
    //倾斜度获取
    double pitch = Math.toDegrees(orientationValues[1]);
    double roll = Math.toDegrees(orientationValues[2]);
    Log.e("mytag", "pitch = " + pitch + ", roll = " + roll);

    //球板移动
    mTable.startBatMove(roll);
    //改变球板大小
    mTable.changeBatBody(pitch);
    break;

    }
    }

    main类:加载mGameView

    部分代码:

     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
    mGameView = new GameView(this, null);
    setContentView(mGameView);
    }
    }

    程序运行截图:

    程序结果截图1 程序运行结果2 程序截图结果3

    总结:这次实验使得我对画布更加了解,还有就是那个安卓传感器的使用。

    相关文章

      网友评论

          本文标题:安卓版传感器利用之带体感操作的打砖块小游戏

          本文链接:https://www.haomeiwen.com/subject/ceftqxtx.html