弹跳球回到android

时间:2012-01-07 05:38:16

标签: java android accelerator

我已经使用SensorManager的加速器示例,其中画布(球)根据设备加速器的旋转更新其位置。这是图像:

enter image description here

如图所示,有一个球和一条线。球的位置经常更新,而线的位置是静态的。

我想让球在接触线时反弹回来。我从3天开始尝试过,但不明白我是怎么做到的。

这是我的代码:

public class ballsensor extends Activity implements SensorEventListener {

    // sensor-related
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;

    // animated view
    private ShapeView mShapeView;

    // screen size
    private int mWidthScreen;
    private int mHeightScreen;

    // motion parameters
    private final float FACTOR_FRICTION = 0.5f; // imaginary friction on the
                                                // screen
    private final float GRAVITY = 9.8f; // acceleration of gravity
    private float mAx; // acceleration along x axis
    private float mAy; // acceleration along y axis
    private final float mDeltaT = 0.5f; // imaginary time interval between each
                                        // acceleration updates

    // timer
    private Timer mTimer;
    private Handler mHandler;
    private boolean isTimerStarted = false;
    private long mStart;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // set the screen always portait
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // initializing sensors
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager
                .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        // obtain screen width and height
        Display display = ((WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        mWidthScreen = display.getWidth();
        mHeightScreen = display.getHeight() - 35;

        // initializing the view that renders the ball
        mShapeView = new ShapeView(this);
        mShapeView.setOvalCenter((int) (mWidthScreen * 0.6),
                (int) (mHeightScreen * 0.6));

        setContentView(mShapeView);

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // obtain the three accelerations from sensors
        mAx = event.values[0];
        mAy = event.values[1];

        float mAz = event.values[2];

        // taking into account the frictions
        mAx = Math.signum(mAx) * Math.abs(mAx)
                * (1 - FACTOR_FRICTION * Math.abs(mAz) / GRAVITY);
        mAy = Math.signum(mAy) * Math.abs(mAy)
                * (1 - FACTOR_FRICTION * Math.abs(mAz) / GRAVITY);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // start sensor sensing
        mSensorManager.registerListener(this, mAccelerometer,
                SensorManager.SENSOR_DELAY_NORMAL);

    }

    @Override
    protected void onPause() {
        super.onPause();
        // stop senser sensing
        mSensorManager.unregisterListener(this);
    }

    // the view that renders the ball
    private class ShapeView extends SurfaceView implements
            SurfaceHolder.Callback {

        private final int RADIUS = 30;
        private final float FACTOR_BOUNCEBACK = 0.50f;

        private int mXCenter;
        private int mYCenter;
        private RectF mRectF;
        private final Paint mPaint;
        private ShapeThread mThread;

        private float mVx;
        private float mVy;

        public ShapeView(Context context) {
            super(context);

            getHolder().addCallback(this);
            mThread = new ShapeThread(getHolder(), this);
            setFocusable(true);

            mPaint = new Paint();
            mPaint.setColor(0xFFFFFFFF);
            mPaint.setAlpha(192);
            mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
            mPaint.setAntiAlias(true);

            mRectF = new RectF();
        }

        // set the position of the ball
        public boolean setOvalCenter(int x, int y) {
            mXCenter = x;
            mYCenter = y;
            return true;
        }

        // calculate and update the ball's position
        public boolean updateOvalCenter() {
            mVx -= mAx * mDeltaT;
            mVy += mAy * mDeltaT;

            System.out.println("mVx is ::" + mVx);
            System.out.println("mVy is ::" + mVy);

            mXCenter += (int) (mDeltaT * (mVx + 0.6 * mAx * mDeltaT));
            mYCenter += (int) (mDeltaT * (mVy + 0.6 * mAy * mDeltaT));

            if (mXCenter < RADIUS) {
                mXCenter = RADIUS;
                mVx = -mVx * FACTOR_BOUNCEBACK;
            }

            if (mYCenter < RADIUS) {
                mYCenter = RADIUS;
                mVy = -mVy * FACTOR_BOUNCEBACK;
            }
            if (mXCenter > mWidthScreen - RADIUS) {
                mXCenter = mWidthScreen - RADIUS;
                mVx = -mVx * FACTOR_BOUNCEBACK;
            }

            if (mYCenter > mHeightScreen - 2 * RADIUS) {
                mYCenter = mHeightScreen - 2 * RADIUS;
                mVy = -mVy * FACTOR_BOUNCEBACK;
            }

            return true;
        }

        // update the canvas.
        @Override
        protected void onDraw(Canvas canvas) {
            if (mRectF != null) {
                mRectF.set(mXCenter - RADIUS, mYCenter - RADIUS, mXCenter
                        + RADIUS, mYCenter + RADIUS);
                canvas.drawColor(0XFF000000);
                // canvas.drawOval(mRectF, mPaint);

                Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
                        R.drawable.stripe1);

                Bitmap ball = BitmapFactory.decodeResource(getResources(),
                        R.drawable.blackwhiteball);

                canvas.drawBitmap(ball, mXCenter - RADIUS, mYCenter - RADIUS,
                        mPaint);
                canvas.drawBitmap(kangoo, 130, 10, null);

            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                int height) {
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            mThread.setRunning(true);
            mThread.start();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            boolean retry = true;
            mThread.setRunning(false);
            while (retry) {
                try {
                    mThread.join();
                    retry = false;
                } catch (InterruptedException e) {

                }
            }
        }
    }

    class ShapeThread extends Thread {
        private SurfaceHolder mSurfaceHolder;
        private ShapeView mShapeView;
        private boolean mRun = false;

        public ShapeThread(SurfaceHolder surfaceHolder, ShapeView shapeView) {
            mSurfaceHolder = surfaceHolder;
            mShapeView = shapeView;
        }

        public void setRunning(boolean run) {
            mRun = run;
        }

        public SurfaceHolder getSurfaceHolder() {
            return mSurfaceHolder;
        }

        @Override
        public void run() {
            Canvas c;
            while (mRun) {
                mShapeView.updateOvalCenter();
                c = null;
                try {
                    c = mSurfaceHolder.lockCanvas(null);
                    synchronized (mSurfaceHolder) {
                        mShapeView.onDraw(c);
                    }
                } finally {
                    if (c != null) {
                        mSurfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}

3 个答案:

答案 0 :(得分:13)

不是尝试修复代码,而是通过开发具有两个组件的软件架构在设计层面工作:物理模型和显示。关键是将问题的物理特性与显示区分开。与显示器分开进行时,物理建模变得更加容易。同样,显示也变得更容易。有两个独立的包 - 一个用于物理,一个用于显示。

从问题的简单版本开始,其中物理世界只有一个点和一条线。模拟从线上反射的点。你有一些代码可以做到这一点。只需将其从当前代码中删除即可。确保物理学能够达到您的预期,而不必担心显示器。

为球设计一个类。球具有速度和位置属性。它有一个移动方法,可以根据一次点击的速度更新位置。移动方法检查它是否与墙相互作用(碰撞)并根据您希望世界拥有的物理变化速度。碰撞检测是通过询问墙壁是否完成来完成的。物理学可以是入射角等于反射角,或者你可以在球上有一个旋转属性来改变球的反弹方式。关键是所有的物理建模都是与显示器分开完成的。同样,您可以为墙创建一个类。最初墙是固定的,但你可以添加移动。好的一点是,如果你设计了球类正确地改变墙壁使其移动不会影响球类的设计。此外,这些物理变化都不会影响显示效果。

制作一个简单地将物理翻译成屏幕上的演示文稿的显示。

从那里可以增加模型的复杂性。将点设为圆。重做物理学以使其适应这种新的复杂性。显示器不会有太大变化,但要将它们分开。

我的CS1类做了同样问题的版本。两年前,我让他们做了一场乒乓球比赛。去年是蜈蚣的一个版本。即将到来的学期他们将突破作为一个项目。当他们将物理模型与显示器分开建模时,他们会将其工作。当他们不这样做时,通常是一团糟。

答案 1 :(得分:1)

物理modyle应在单独的线程中运行,并使用最佳可用时间分辨率进行位置更新。 (毫秒应该足够了)这就是我设计gameloop的方式:

    lastFrameTime = System.currentTimeMillis();

    // as long as we run we move
    while (state == GameState.RUNNING) {
        currentFrame++;
        timeNow = System.currentTimeMillis();

        // sleep until this frame is scheduled
        long l = lastFrameTime + FRAME_DELAY - timeNow;
        updatePositions();
        redraw();       
        if (l > 0L) {
            try {
                Thread.sleep(l);
            }
            catch (Exception exception) {
            }
        } else {
            // something long kept us from updating, reset delays
            lastFrameTime = timeNow;
            l = FRAME_DELAY;
        }

        lastFrameTime = timeNow + l;
        // be polite, let others play
        Thread.yield();
    }

放弃对线程的控制非常重要,因为UI任务将处理事件和hive命令到phyiscs引擎。

至于碰撞检测 - 数学非常简单。你的线是垂直的,你必须检查线和中心的x-coord的差异是否小于半径 - 然后反转速度的x-componen

答案 2 :(得分:0)

您可以使用Rect.intersects(Rect,Rect)来检测碰撞。使用位图宽度和高度来设置新的Rects。

这是一个肮脏的例子:

import java.util.Timer;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

public class ballsensor extends Activity implements SensorEventListener {

// sensor-related
private SensorManager mSensorManager;
private Sensor mAccelerometer;

// animated view
private ShapeView mShapeView;

// screen size
private int mWidthScreen;
private int mHeightScreen;

// motion parameters
private final float FACTOR_FRICTION = 0.5f; // imaginary friction on the
                                            // screen
private final float GRAVITY = 9.8f; // acceleration of gravity
private float mAx; // acceleration along x axis
private float mAy; // acceleration along y axis
private final float mDeltaT = 0.5f; // imaginary time interval between each
                                    // acceleration updates

// timer
private Timer mTimer;
private Handler mHandler;
private final boolean isTimerStarted = false;
private long mStart;

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // set the screen always portait
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // initializing sensors
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mAccelerometer = mSensorManager
            .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    // obtain screen width and height
    final Display display = ((WindowManager) this
            .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    mWidthScreen = display.getWidth();
    mHeightScreen = display.getHeight() - 35;

    // initializing the view that renders the ball
    mShapeView = new ShapeView(this);
    mShapeView.setOvalCenter((int) (mWidthScreen * 0.6),
            (int) (mHeightScreen * 0.6));

    setContentView(mShapeView);

}

@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {

}

@Override
public void onSensorChanged(final SensorEvent event) {
    // obtain the three accelerations from sensors
    mAx = event.values[0];
    mAy = event.values[1];

    final float mAz = event.values[2];

    // taking into account the frictions
    mAx = Math.signum(mAx) * Math.abs(mAx)
            * (1 - FACTOR_FRICTION * Math.abs(mAz) / GRAVITY);
    mAy = Math.signum(mAy) * Math.abs(mAy)
            * (1 - FACTOR_FRICTION * Math.abs(mAz) / GRAVITY);
}

@Override
protected void onResume() {
    super.onResume();
    // start sensor sensing
    mSensorManager.registerListener(this, mAccelerometer,
            SensorManager.SENSOR_DELAY_NORMAL);

}

@Override
protected void onPause() {
    super.onPause();
    // stop senser sensing
    mSensorManager.unregisterListener(this);
}

// the view that renders the ball
private class ShapeView extends SurfaceView implements
        SurfaceHolder.Callback {

    private final int RADIUS = 30;
    private final float FACTOR_BOUNCEBACK = 0.50f;

    private int mXCenter;
    private int mYCenter;
    private final RectF mRectF;
    private final Paint mPaint;
    private final ShapeThread mThread;

    private float mVx;
    private float mVy;
    private final Rect lineRect = new Rect();
    private final Rect ballRect = new Rect();

    public ShapeView(final Context context) {
        super(context);

        getHolder().addCallback(this);
        mThread = new ShapeThread(getHolder(), this);
        setFocusable(true);

        mPaint = new Paint();
        mPaint.setColor(0xFFFFFFFF);
        mPaint.setAlpha(192);
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setAntiAlias(true);

        mRectF = new RectF();
    }

    // set the position of the ball
    public boolean setOvalCenter(final int x, final int y) {
        mXCenter = x;
        mYCenter = y;
        return true;
    }

    // calculate and update the ball's position
    public boolean updateOvalCenter() {
        mVx -= mAx * mDeltaT;
        mVy += mAy * mDeltaT;

        System.out.println("mVx is ::" + mVx);
        System.out.println("mVy is ::" + mVy);

        mXCenter += (int) (mDeltaT * (mVx + 0.6 * mAx * mDeltaT));
        mYCenter += (int) (mDeltaT * (mVy + 0.6 * mAy * mDeltaT));

        if (mXCenter < RADIUS) {
            mXCenter = RADIUS;
            mVx = -mVx * FACTOR_BOUNCEBACK;
        }

        if (mYCenter < RADIUS) {
            mYCenter = RADIUS;
            mVy = -mVy * FACTOR_BOUNCEBACK;
        }
        if (mXCenter > mWidthScreen - RADIUS) {
            mXCenter = mWidthScreen - RADIUS;
            mVx = -mVx * FACTOR_BOUNCEBACK;
        }

        if (mYCenter > mHeightScreen - 2 * RADIUS) {
            mYCenter = mHeightScreen - 2 * RADIUS;
            mVy = -mVy * FACTOR_BOUNCEBACK;
        }

        if(Rect.intersects(lineRect, ballRect)){
            mVx = -mVx * FACTOR_BOUNCEBACK;
            mVy = -mVy * FACTOR_BOUNCEBACK;
             mXCenter += (int) (mDeltaT * (mVx + 0.6 * mAx * mDeltaT)) * 5;
             mYCenter += (int) (mDeltaT * (mVy + 0.6 * mAy * mDeltaT)) * 5;
        }

        return true;
    }

    // update the canvas.
    @Override
    protected void onDraw(final Canvas canvas) {
        if (mRectF != null) {
            mRectF.set(mXCenter - RADIUS, mYCenter - RADIUS, mXCenter
                    + RADIUS, mYCenter + RADIUS);
            canvas.drawColor(0XFF000000);
            // canvas.drawOval(mRectF, mPaint);

            final Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
                    R.drawable.blankcard);
            lineRect.set(130, 10, 130 + kangoo.getWidth(), 10 + kangoo.getHeight());

            final Bitmap ball = BitmapFactory.decodeResource(getResources(),
                    R.drawable.blankcard);
            ballRect.set(mXCenter - RADIUS,  mYCenter - RADIUS, mXCenter - RADIUS + ball.getWidth(),  mYCenter - RADIUS + ball.getHeight());

            canvas.drawBitmap(ball, mXCenter - RADIUS, mYCenter - RADIUS,
                    mPaint);
            canvas.drawBitmap(kangoo, 130, 10, null);

        }
    }

    @Override
    public void surfaceChanged(final SurfaceHolder holder, final int format, final int width,
            final int height) {
    }

    @Override
    public void surfaceCreated(final SurfaceHolder holder) {
        mThread.setRunning(true);
        mThread.start();
    }

    @Override
    public void surfaceDestroyed(final SurfaceHolder holder) {
        boolean retry = true;
        mThread.setRunning(false);
        while (retry) {
            try {
                mThread.join();
                retry = false;
            } catch (final InterruptedException e) {

            }
        }
    }
}

class ShapeThread extends Thread {
    private final SurfaceHolder mSurfaceHolder;
    private final ShapeView mShapeView;
    private boolean mRun = false;

    public ShapeThread(final SurfaceHolder surfaceHolder, final ShapeView shapeView) {
        mSurfaceHolder = surfaceHolder;
        mShapeView = shapeView;
    }

    public void setRunning(final boolean run) {
        mRun = run;
    }

    public SurfaceHolder getSurfaceHolder() {
        return mSurfaceHolder;
    }

    @Override
    public void run() {
        Canvas c;
        while (mRun) {
            mShapeView.updateOvalCenter();
            c = null;
            try {
                c = mSurfaceHolder.lockCanvas(null);
                synchronized (mSurfaceHolder) {
                    mShapeView.onDraw(c);
                }
            } finally {
                if (c != null) {
                    mSurfaceHolder.unlockCanvasAndPost(c);
                }
            }
        }
    }
}
}

需要改进,但可能会让你走上正轨。