我正在尝试制作一款小型游戏,您可以在屏幕上投掷硬币。当我在寻找那种动画时,我找到了这个页面
http://mobile.tutsplus.com/tutorials/android/android-gesture/
我设法根据我的目标自定义事件,但我无法在屏幕上设置边界,以便硬币(位图)在边缘时会反弹。
我尝试了几次计算,但最后硬币根据边缘上的接触点奇怪地移动。
根据网站上的工作代码,有人可以帮助我吗
答案 0 :(得分:0)
以下是我的乒乓游戏的示例代码。每个对象都有位置(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();
}