我以 SensorManager 的加速器为例,其中 Canvas (球)根据设备加速器的旋转来更新其位置。这是图像:

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

我想让球在触线时反弹回来。我从 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);
                    }
                }
            }
        }
    }
}

最佳答案

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

从一个更简单的问题开始,其中物理世界只有一个点和一条线。对线外反射的点进行建模。你有一些代码可以做到这一点。只需将其从当前代码中删除即可。确保物理性能符合您的预期,而不必担心显示。

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

制作一个简单地将物理转换为屏幕上的演示文稿的显示。

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

我有我的 CS1 类做同样问题的版本。两年前,我让他们制作乒乓球游戏。去年的一个版本的蜈蚣。在下学期,他们将 Breakout 作为一个项目。当他们将物理模型与显示器分开时,他们就可以工作了。当他们不这样做时,通常是一团糟。

关于java - 反弹球回安卓,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8767676/

10-12 20:49