【问题标题】:Bouncing back on the edges在边缘反弹
【发布时间】:2013-06-17 13:46:02
【问题描述】:

我正在尝试制作一个可以在屏幕上投掷硬币的小游戏。当我在寻找那种动画时,我发现了这个页面

http://mobile.tutsplus.com/tutorials/android/android-gesture/

我设法根据我的目标自定义事件,但我无法在屏幕上设置边界,以便硬币(位图)在到达边缘时会反弹。

我尝试了几次计算,但最终硬币根据边缘上的接触点奇怪地移动。

根据网站上的工作代码,有人可以帮助我吗

【问题讨论】:

    标签: 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();
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多