For a game of table tennis, the goal is that when the player hits the ball, the opponent (the computer) will move to the position where the ball will land in order to hit it back to the player.
Said another way, given a ball in 3D space with an XYZ vector for its velocity, how can I calculate an XYZ velocity vector that will result in the position of the computer player being approximately where the ball will land?
For my coordinate system is, Y is up/down, Z is left and right of the table, and X is forward backward (toward or away from the table)... So, I know I can simply just set the player's z velocity to match the ball's z velocity to match the direction, but I need to know how to find the appropriate X velocity so that the player will move backward / forward depending on how fast the ball is traveling + taking into account the height of the ball + gravity, etc.
Seeing that the initial ball height is different than the table and the floor, I did some research and learned that the quadratic formula was the best way to solve this problem...
serveToTable = (-ball.vel.y + Math.sqrt((ball.vel.y * ball.vel.y) - (4 * (gravity * 0.5) * (tableY - ball.pos.y)))) / gravity; tableToFloor = (-ball.vel.y + Math.sqrt((ball.vel.y * ball.vel.y) - (4 * (gravity * 0.5) * (floorY - ball.pos.y)))) / gravity; duration = serveToTable + tableToFloor; player.pos.x = ball.pos.x + (ball.vel.x * duration); player.pos.z = ball.pos.z + (ball.vel.z * duration);
This, kind of works.. But it seems the player will go to the ball 2-4 times and then miss the ball. Sometimes by quite a lot.