Question

I am trying to make a small game where you can fling a coin on the screen. while i was searching for that kind of animation i found this page

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

I managed to customise the events according to my aim, but i couldn't manage to set boundaries on the screen so that the coin(bitmap) will bounce back when it comes to the edges.

I tried several calculations but in the end the coin moves weirdly based on the contact points on the edges.

Can someone help me about it, according to the working code on the website

Was it helpful?

Solution

Below is a sample code from my pong game. Each object has position (x,y) and its speed. Movement is speed applied to position. One extra info is that the screen coordinate system starts from the left top corner. Y axis go down but increasing. Since screen coordinates start from 0, the boundaries become screen.width -1 and 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();

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top