0
\$\begingroup\$

I am quite the beginner in XNA. I have only recently started using GameComponents. I have a multiplayer game called Better Pong. I move the ball (which is an object) by incrementing the Vector2 (the position) of the ball by the velocity Vector2 and updating the hitbox Rectangle.

However, by having very large speeds (such as (12,12)) the ball might go through the paddle since it just skips through the Paddle's Rectangle "hitbox".

Is there a way to make the ball make smaller movements, so it doesn't go through the paddle (but still move fast)?

\$\endgroup\$

marked as duplicate by MichaelHouse Nov 26 '14 at 16:39

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1
\$\begingroup\$

You need to either interpolate or extrapolate the collision. Basically this means instead of just checking the collision of the object where it is NOW, check the collision of the object with where it is and where it WILL BE or WAS, then check x number of times in between those positions.

Vector2 pos = ball.position;
Vector2 prevPos = ball.previousPosition; // You'll have to keep track of where the ball was 1 frame ago.

for (int i=0; i<COLLISION_PRECISION; i++)
{
    Vector2 testPos = lerp(prevPos, pos, i/COLLISION_PRECISION);
    if (PointInsideRect(testPos, paddleRect))
    {
        ball.position = testPos;
        // Do any collision reactions
        break;
    }
}

In this example, you'd check for collisions from where the ball was last frame to where it currently is, and a number of points in between those points equal to COLLISION_PRECISION. The higher the COLLISION_PRECISION, the less chance your ball will move through a paddle.

EDIT: I forgot to mention, this is pseudo code, you shouldn't be copy pasting it or anything, it's just kind of an outline of what you have to do.

\$\endgroup\$
  • \$\begingroup\$ What does the lerp function do? I googled it but the explanations are really vague.. I do sorta understand this, though :D \$\endgroup\$ – Ilan321 Nov 26 '14 at 16:49
  • \$\begingroup\$ Oh sorry lerp is a "linear interpolation". It takes 2 values, and gives you a value in between them with a percentage kind of. So if you had two points { 1, 1 } and { 3, 3 } and you got the linear interpolation at 0.5 (50%) you would get the middle point between the two vectors { 2, 2 }. You just have to think of it as "(100%-X%) first value + (X%) of the second value". It's kind of weird to wrap your head around, but you'll get it. \$\endgroup\$ – Heckman Nov 26 '14 at 18:32
  • \$\begingroup\$ Oh I think I implemented it a bit on my own, except my game's bork now. I'll keep working on it :) \$\endgroup\$ – Ilan321 Nov 26 '14 at 18:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.