Sign in to follow this  
jlewicki

Error in wall collision, 2d

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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this