# Error in wall collision, 2d

This topic is 4457 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm getting some weird result with my wall collision segements for a pong clone game of mine: I'd say 96% of the time the ball reflects properly off the walls. When it doesnt reflect, it seems to get stuck in the wall, bouncing up and down and moving parallel with the wall, it will either randoming get "unstuck" or stay that way until it gets past a paddle and scores.
void SpriteDemo::updateBall(float dt)
{
ball.pos += ball.direction * ball.velocity * dt;

if(ball.pos.x <= -500)
{
lockUp();

scoreAI++;

if(scoreAI >= 5)
{
stateOn(LOSS_SCREEN);
}
else
{
stateOn(RESULTS_SCREEN);
}
}
else if(ball.pos.x >= 500)
{
lockUp();

scoreHuman++;

if(scoreHuman >= 5)
{
stateOn(WIN_SCREEN);
}
else
{
stateOn(RESULTS_SCREEN);
}
}
else
{
if((ball.pos.y - 16) <= -365.0f)			//handles collision at bottom of the screen
{
if(ball.angle < 4.71f)
{
ball.angle = ((4.71f) - ball.angle) + 4.71f;
}
else if(ball.angle > 4.71f)
{
ball.angle = 4.71f - (ball.angle - (4.71f));
}

ball.direction 	= D3DXVECTOR3(-sinf(ball.angle), cosf(ball.angle), 0.0f);	//change direction
}
if((ball.pos.y + 16) >= 330.0f)			//handles collision at top of the screen
{
if(ball.angle < 1.57f)
{
ball.angle = ((1.57f) - ball.angle) + 1.57f;
}
else if(ball.angle > 1.57f)
{
ball.angle = 1.57f - (ball.angle - (1.57f));
}

ball.direction 	= D3DXVECTOR3(-sinf(ball.angle), cosf(ball.angle), 0.0f);	//change direction
}
}
}



##### Share on other sites
Usually the problem is that the ball moves so fast, or at such an angle that it goes deep in the paddle and when it bounces back it is still in the paddle inverting the direction.

One way to solve it would be to instead of inverting the direction, always set the direction to negative y or positive y, so even if the bal is still in the paddle it will only set the direction to what is already is and the ball will move away from the paddle

My preferred way would be to detect the collision, set the location of the ball (midpoint) to paddle.top+radius_ball (if it is the bottom paddle), so it is directly connected to the paddle instead of in it.. if you invert the direction now you are certain that the ball is out of the paddle, avoiding lockups. It will also look better since the ball really collides with the paddle.

Hope that works for you.
Greetings.

1. 1
Rutin
42
2. 2
3. 3
4. 4
5. 5

• 9
• 27
• 20
• 14
• 14
• ### Forum Statistics

• Total Topics
633387
• Total Posts
3011607
• ### Who's Online (See full list)

There are no registered users currently online

×