i am trying to implement Deceleration on the bouncy ball. i am able to move the ball up and down but i wanted to add Declaration so when i drop the ball from height it jumps then strike the ground bounce once again and slowly slowly its speed decreases and stop at the end.
Here is My code
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView;
public class AnimatedView extends ImageView{
private Context mContext;
int x = -1;
int y = -1;
private int xVelocity = 0;
private int yVelocity = 25;
private Handler h;
private final int FRAME_RATE = 20;
public AnimatedView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
h = new Handler();
}
private Runnable r = new Runnable() {
@Override
public void run() {
invalidate();
}
};
protected void onDraw(Canvas c) {
BitmapDrawable ball = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.ball);
if (x<0 && y <0) {
x = this.getWidth()/2;
y = this.getHeight()/2;
} else {
x += xVelocity;
y += yVelocity;
if ((x > this.getWidth() - ball.getBitmap().getWidth()) || (x < 0)) {
xVelocity = xVelocity*-1;
}
if ((y > this.getHeight() - ball.getBitmap().getHeight()) || (y < 0)) {
yVelocity = yVelocity*-1;
}
}
c.drawBitmap(ball.getBitmap(), x, y, null);
h.postDelayed(r, FRAME_RATE);
}
Hope Anyone Can Help me.
Thanks in Advance
Acceleration is to velocity as velocity is to position. You just need to do what you're doing with your position to your velocity.
The simplest solution is to add
to the top of onDraw where yAccel is a int that you want added to the yVelocity every tick. Based on your velocity values
might be appropriate.
edit: You should also add checks to ensure the ball does not go into the ground. I added these in the blocks that reverse the velocity, the following code works for me. If it don't work for you, there might be something wrong with another part of your project.