使球弹起并最终停止

使球弹起并最终停止

我已经编写了一些代码来使用方向传感器在屏幕上移动球。我希望球碰到屏幕底部时能够反弹,就像在重力作用下一样。有人可以在我现有的代码中帮助实现物理吗?翻转速度似乎无效。这是我的舞会:

package perseus.gfx.test;

import everything

public class Ball extends View  {
RectF lol;
Paint paint, lpaint;
Bitmap bitmap;
Canvas canvas;
private float ballx = 150;
private float bally = 140;
private double speedx = 0;
private double speedy = 0; //ignore
private double accx, accy=0;
private float rad = 20;
private float mult = 0.5f;
private double xv, yv, xS, yS;
int width, height;
int xmax, ymax;
int xmin, ymin;

public Ball(Context context) {
    super(context);
    lol = new RectF();
    paint = new Paint();
    paint.setColor(Color.CYAN);
    lpaint = new Paint();
    lpaint.setColor(Color.GRAY);
}
public void moveBall()  {

    xv = accx * mult;
    yv = accy * mult;

    xS = xv * mult;
    yS = yv * mult;

    ballx -= xS;
    bally -= yS;

    // Collision detection
    if (ballx + rad > xmax) {

         ballx = xmax-rad;
    }
    else if (ballx - rad < 0) {

         ballx = rad;
    }
    if (bally + rad > 2*ymax/3) //Shouldn't take up the whole screen
    {

        bally = 2*ymax/3 - rad;
    }

    else if (bally - rad < 0) {

         bally =  rad;
    }

    try {
        Thread.sleep(20);
    }   catch(InterruptedException e) {}

    invalidate();
}
@Override
public void onMeasure(int widthM, int heightM)
{
    width = View.MeasureSpec.getSize(widthM);
    height = View.MeasureSpec.getSize(heightM);
    xmax = width-1;
    ymax = height-1;
    xmin = 0;
    ymin = 0;
    setMeasuredDimension(width, height);
    bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    canvas = new Canvas(bitmap);


}
@Override
public void onDraw(Canvas canvas)
{
    canvas.drawBitmap(bitmap, 0, 0, paint);
    lol.set(ballx - rad, bally-rad, ballx + rad, bally+rad);
    canvas.drawLine(0, 2*height/3, width, 2*height/3, lpaint);
    canvas.drawOval(lol, paint);
    canvas.drawText(xv + " " + yv, 0, height/2, lpaint);
    canvas.save();
    moveBall();
    canvas.restore();

}
}

最佳答案

因此关键是要增加一点摩擦,在moveBall()的每一步都只需消除一点加速度(负!)。例如。

    float friction = -0.001;

    xv = accx * mult + friction;
    yv = accy * mult + friction;


然后根据需要调整可变摩擦。对于碰撞,您需要反转速度,例如在底部反弹:

    bally = -bally;

关于android - 使球弹起并最终停止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9031039/

10-11 14:50