【问题标题】:Bouncing back on the edges在边缘反弹
【发布时间】:2013-06-17 13:46:02
【问题描述】:
【问题讨论】:
标签:
android
animation
android-animation
android-canvas
onfling
【解决方案1】:
下面是我的乒乓球游戏的示例代码。每个对象都有位置 (x,y) 和它的速度。运动是应用于位置的速度。一个额外的信息是屏幕坐标系从左上角开始。 Y轴下降但增加。由于屏幕坐标从 0 开始,边界变为 screen.width -1 和 screen.height -1
@Override
public void onDraw(Canvas c){
p.setStyle(Style.FILL_AND_STROKE);
p.setColor(0xff00ff00);
// If ball's current x location plus the ball diameter is greater than screen width - 1, then make speed on x axis negative. Because you hit the right side and will bounce back to left.
if((Px+ballDiameter) > width - 1){
Vx = -Vx;
}
// If ball's current y location plus the ball diameter is greater than screen height -1, then make speed on y axis negative. Because you hit the bottom and you will go back up.
if((Py + ballDiameter) > height - 1){
Vy = -Vy;
}
// If current x location of the ball minus ball diameter is less than 1, then make the speed on x axis nagative. Because you hit to the left side of the screen and the ball would bounce back to the right side
if((Px - ballDiameter) < 1){
Vx = -Vx;
}
// If current y location of the ball minus ball diameter is less than 1, then make the speed on y axis negative. Because the ball hit the top of the screen and it should go down.
if((Py - ballDiameter ) <1){
Dy = 1;
Vy = -Vy;
}
Px += Vx; // increase x position by speed
Py += Vy; // increase y position by speed
c.drawCircle(Px, Py, ballDiameter, p);
invalidate();
}