Reputation: 113
I have pong balls that are being generated very consistently, but the rates change dynamically. So in a given second, there could be 1 pong ball that's being drawn and translating across the screen (constantly from left to right), or 50.
I have a pong paddle that responds based on the generation of these balls, and it's supposed to "catch" every one of the balls that's being sent towards its destination. The x coordinate is always the same, because the pong paddle never moves, but the y coordinate is randomly generated.
Here's an extremely similar (if not identical) example of what I'm doing: http://www.youtube.com/watch?v=HeWfkPeDQbY
I have a lot of this code already written, but I'm afraid my design for catching the balls is incorrect/inefficient. It works, but the paddle very easily becomes out of sync with the balls that are being thrown towards it.
The way I'm currently doing this is by putting each ball object into a global array, and the paddle pops the next ball off of this queue and uses basic arithmetic to calculate the speed at which it needs to translate to the y coordinate of the next ball.
Is there a more efficient way of doing this?
Upvotes: 1
Views: 597
Reputation: 8768
I'll assume the issue is that the motion of each ball (and the paddle) is controlled by a separate timer. Since there are no guarantees about the exactness of js timers, there are really no guarantees about how many, many timers will interact.
Two broad approaches to correct the problem are:
Instead of using raphaeljs animation primitives, implement a synchronous animation yourself with setTimer, updating the position of each ball (and the paddle) in sync. Then any timer-stutters apply consistently across all elements in your universe.
Use feedback to course-correct the paddle position, e.g. by having a special setTimer that periodically looks at how close the paddle is to where it needs to be, and if necessary calls .stop() on the paddle's animation in order to re-execute with more aggressive parameters, closing the gap.
Upvotes: 2