This site requires JavaScript, please enable it in your browser!
Greenfoot back
TheGrape
TheGrape wrote ...

2013/5/17

I need help with a game I'm making

TheGrape TheGrape

2013/5/17

#
I'm just a beginner and I'm creating a ping pong game for a project. I can't figure out how to make it so when the ball hits the paddle to moves the opposite direction towards the opponent. I also am wondering how to reset the ball when a point is scored. I am using the scoreboard that is given in Greenfoot but I need a little help.
Entity1037 Entity1037

2013/5/17

#
This is easy. First, define an integer outside of a method that holds the amount of cells you want the ball to move every time the code runs. So it should look like:
import Greenfoot.*;

public class Ball
{
    int xmove=2;
    int ymove=2;

    public void act()
    {
        //Make sure this is in the act method, or a method called from the act method
        if (getOneIntersectingObject(Paddle.class)!=null){
            xmove=-xmove;
           setLocation(getX()+xmove,getY());
        }
        setLocation(getX()+xmove,getY()+ymove);
    }
}
You need a second setLocation method due to it sometimes not moving away from the paddle enough, and it getting stuck inside of it. I hope this helps.
TheGrape TheGrape

2013/5/17

#
OK thank you so much! I'm going to try to add this to my code tomorrow, hopefully it works.
You need to login to post a reply.