0

I'm having some trouble getting the ball to move when the user clicks at the start of the game. I have the code below positioned in main, right after everything is instantiated, and before the while (true) loop. I created double xvel and double yvel global variables. When I run breakout, everything sets up correctly and the paddle follows my mouse, but the ball won't move on my click. Any help is appreciated. Thanks!

xvel = drand48();
yvel = - 2.0 * drand48();

GEvent start = getNextEvent(MOUSE_EVENT);    

if (start != NULL)
{
    if (getEventType(start) == MOUSE_CLICKED)
    {
        move(ball, xvel, yvel);
    }
}

1 Answer 1

1

Each instruction listed here will do each task exactly once. Translating your code into pseudo-code, it's doing roughly the following:

set xvel to a random number between 0 and 1
set yvel to a random number between -2 and -1

check if there is an event in the queue

if the event is a mouse click event then move the ball by the distance in xvel and yvel

This all happens once, before your loop.

There are two problems with this.

  1. getNextEvent is intended to be used inside a loop. If you want to pause your program and wait for an event, you need to use waitForClick(). See the documentation for gevents!

  2. Likewise, the move() statement only moves the object once, by a specified distance. To keep the object moving, you need to keep executing move() inside a loop. See the documentation for gobjects.

3
  • @Kareem Thanks for the edits, but I'm not sure I agree with all your changes. While waitForClick() will work in this scenario, I don't think it's necessarily correct for all scenarios. If the code is moved into the loop it would make sense to use waitForEvent for a frame rate timer for example. Of course I may be mistaken. Also, GEvent and GObject are spelled as such in the documentation so I'm not sure why you changed the case? Jul 18, 2014 at 11:47
  • Hi, Luke! Sorry if I miss understood something! I thought you already meant waitForClick() and you also added links to the whole gobjects and gevents header files not a specific type like GObject or GEvent. You can still edit your answer of course, so feel free to do that! :)
    – kzidane
    Jul 18, 2014 at 12:14
  • @Kareem I see what you mean about the links to the headers vs the objects. I'll leave the answer as is - these comments explain everything clearly. Jul 18, 2014 at 12:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .