2012-01-27 25 views
2

我寫了一些代碼,使用方向傳感器在屏幕上移動球。我想讓球在碰到屏幕底部時彈起來,有點像重力。有人可以幫助我在現有的代碼中實現物理?翻轉速度似乎不起作用。這是我的球類:使球彈跳並最終靜止

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(); 

} 
} 

回答

1

因此,關鍵是要增加一點摩擦,只是在每一步中moveBall刪除加速度(負!)的一點點()。例如。

float friction = -0.001; 

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

然後根據您的需要調整變量摩擦。對於碰撞,你需要反轉速度,例如反彈在底部:

bally = -bally; 
+0

不,這似乎並沒有工作.. 我想是這傢伙做: http://vimeo.com/3792427 但他的代碼看起來完全不同礦。 :/ – 2012-01-27 13:50:48

+0

視頻就像Scalar傳達的一樣。由於手機的加速度計總是知道由於地球引力而導致哪個方向下降。當球可以朝這個方向自由移動時,球就朝着這個方向加速。它最終會因爲像Scalar那樣持續的摩擦而停下來,或者通過減少在每個牆壁反彈時的一個因子量來減少動量。我沒有看到它在牆壁上反彈,所以它是不斷摩擦的。 – 2012-01-30 17:00:45

+0

@ user1162533也許它關於變量是如何由加速度計設置的。您能否在這種情況下提供代碼? – Scalarr 2012-01-30 20:40:27