我正试图在弹力球上实施减速。我可以上下移动球,但是我想添加宣言,所以当我从高处摔下球时它会跳起然后再次撞击地面反弹然后慢慢慢慢地减速并停在最后。
这是我的代码
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);
}
希望任何人都可以帮助我。
先谢谢
答案 0 :(得分:1)
当速度到达位置时,加速度就是速度。你只需要根据你的速度做你正在做的事情。
最简单的解决方案是添加
yVelocity += yAccel;
到onDraw的顶部,其中yAccel是一个int,你想要在每个tick中添加到yVelocity。根据您的速度值
private int yAccel = -2;
可能合适。
编辑:您还应该添加支票以确保球不会进入地面。我在反转速度的块中添加了这些,以下代码适用于我。如果它对您不起作用,则项目的另一部分可能存在问题。
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 int yAccel = 2;
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) {
yVelocity += yAccel;
BitmapDrawable ball = (BitmapDrawable) mContext.getResources()
.getDrawable(R.drawable.cakes);
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;
x = Math.min(this.getWidth() - ball.getBitmap().getWidth(), x);
x = Math.max(0, x);
}
if ((y > this.getHeight() - ball.getBitmap().getHeight())
|| (y < 0)) {
yVelocity = (int)(yVelocity * -0.8f);
y = Math.min(this.getHeight() - ball.getBitmap().getHeight(), y);
y = Math.max(0, y);
}
}
c.drawBitmap(ball.getBitmap(), x, y, null);
h.postDelayed(r, FRAME_RATE);
}
}