Jump to content

  • Log In with Google      Sign In   
  • Create Account






Arkanong part 1: Porting for the sake of sanity

Posted by molehill mountaineer, 15 November 2013 · 470 views

arkanong
Last year I decided that I had enough of my procrastrination (and several other bad habits) and began a process of self-reformation.
Part of this undertaking was the development of a small framework with which I could make a pong clone. The plan was to build the engine as an educational exercise, produce several small games and perhaps form a development partnership with somebody on this site down the road.

This is what I managed to put together:


Attached Image


It's pong meets breakout with several balls - touching the other player's balls (heh heh) will convert them to yours and vice versa. The paddle can move in eight directions up to a certain vertical limit and the bricks contain powerups (not yet implemented except a single "cheat key" which will cause the blue balls to move much faster).


This took a long time to make, as I have school and 'real world' projects competing for my time.
The real problem though, was that every single step of the way was new to me.
Drawing quads on screen, batching sprites, implementing physics for bouncing balls off each other, working with sound, writing code that generates textured quads because for some reason directX10 doesn't support drawing text on screen, etcetera.
Although the code works, the 'engine' and game quickly became a patchwork of messy amateur implementations. Check this out: (don't read the whole thing unless you're a masochist)



void PongPrototype::performCollisionChecks()

{

	HitRegion* playerRegion			= m_pHumanPlayer->getPaddle()->getHitRegion();

	//HitRegion* enemyRegion			= m_pEnemyPaddle->getHitRegion();

	HitRegion* enemyRegion			= m_pEnemyPlayer->getPaddle()->getHitRegion();



	HitRegion* ballRegion			= NULL;

	HitRegion* brickRegion			= NULL;

	Ball*	  currentBall			= NULL;

	//



	//check player collisions against level border and correct if necessary

	if(checkBorderCollision(playerRegion))

	{

		correctPaddleOverschoot(m_pHumanPlayer->getPaddle());

	}

	if(checkBorderCollision(enemyRegion))

	{

		//correctPaddleOverschoot(m_pEnemyPaddle);

		correctPaddleOverschoot(m_pEnemyPlayer->getPaddle());

	}





	//iterate over balls and perform collision checks 

	std::vector<Ball*>::iterator it = m_balls.begin();

	for(it; it != m_balls.end(); ++it)

	{

		currentBall = (*it);

		if(currentBall != NULL)  //is there a ball to check?

		{



			ballRegion = (*it)->getHitRegion();



			//check ball collision against border 

			if(checkBorderCollision(ballRegion))

			{

				correctBallovershoot(currentBall);

				bounceBallOffWall(currentBall);

			}





	//		

	//		//it's important that we check the ball against paddle (in checkRegionCollision) and not the other way around

	//		//-> because of the way that the collision is calculated a larger hitregion checked against a 

	//		//smaller one will not return true. 

	//		//check ball collision against players

			if(m_pParentProject->checkRegionCollision(ballRegion, playerRegion)) //did ball hit player paddle?

			{

				bounceBallOffPaddle(currentBall, m_pHumanPlayer->getPaddle());

			}

			if(m_pParentProject->checkRegionCollision(ballRegion, enemyRegion)) //did ball hit player paddle?

			{

				//bounceBallOffPaddle((*it), m_pEnemyPaddle);

				bounceBallOffPaddle(currentBall, m_pEnemyPlayer->getPaddle());

			}





	//		//iterate over bricks and perform checks





			//iterate over bricks and perform collision checks 

			std::vector<PowerupBrick*>::iterator brickIt = m_bricks.begin();

			for(brickIt; brickIt != m_bricks.end(); ++brickIt)

			{

				if((*brickIt) != NULL)  //is there a brick to check?

				{

					brickRegion = (*brickIt)->getHitRegion();

					if(m_pParentProject->checkRegionCollision(ballRegion, brickRegion))

					{

						bounceBallOffBrick((*brickIt), currentBall);

					}

				}

			}

	

			//finally iterate over entire ball vector to perform collision checks with other balls

			std::vector<Ball*>::iterator it2 = m_balls.begin();

			for(it2; it2 != m_balls.end(); ++it2)

			{

				//we've got to make sure that there is a ball to collide and that 

				//we don't "collide" with ourself

				if((*it2 != NULL) && (it2 != it))

				{

					HitRegion* otherBallRegion = (*it2)->getHitRegion();



					//did the balls hit each other?

					if(m_pParentProject->checkRegionCollision(ballRegion, otherBallRegion))

						bounceBallsOffEachOther(currentBall, *it2);

				}

			}

		}

	}



}









//this function moves the ball back a little if it's gone past the window edges

void PongPrototype::correctBallovershoot(Ball* p_ball)

{

	

	floatRect region = p_ball->getHitRegion()->getRegion();

	

	XMFLOAT2 offset;

	offset.x = 0.0f;

	offset.y = 0.0f;



	if(region.left <= 0)

		offset.x -= region.left; //negative number so we subtract



	if(region.right > SOLIPSIST.getWindowWidth())

		offset.x -= (region.right - SOLIPSIST.getWindowWidth());



	//hit top or bottom? adjust overshoot and flip y direction

	if(region.bottom <= 0)

		offset.y -= region.bottom;



	if(region.top > SOLIPSIST.getWindowHeight())

		offset.y -= (region.top - SOLIPSIST.getWindowHeight());





	//adjust overshoot

	p_ball->move(offset);



}











void PongPrototype::bounceBallsOffEachOther(Ball* p_ballOne, Ball* p_ballTwo)

{

	

	//hitregion is a bit smaller than the actual ball so we add a margin

	int ballOneRadius = (p_ballOne->getHitRegion()->getRegionWidth()  / 2) + 2;

	int ballTwoRadius = (p_ballTwo->getHitRegion()->getRegionWidth()  / 2) + 2;



	//find out the normal to the collision plane (by normalizing the distance between the centerpoints

	//position = centerpoint

	XMFLOAT2 ballOnePosition = p_ballOne->getBitmap()->getPosition();

	XMFLOAT2 ballTwoPosition = p_ballTwo->getBitmap()->getPosition();



	XMFLOAT2 normalVector;

	normalVector.x = ballOnePosition.x - ballTwoPosition.x;

	normalVector.y = ballOnePosition.y - ballTwoPosition.y;



	//find out magnitude (=length) of directional vector by taking square root of squared components

	//(brush up on vector math if you don't understand this bit)

	float normalMagnitude = sqrt((normalVector.x * normalVector.x) + (normalVector.y * normalVector.y));





	if(normalMagnitude <= (ballOneRadius + ballTwoRadius)) //collision? 

	{

		//move balls back a little to correct any overshoot so the hitregions don't get stuck inside eachother

		float overshoot =  (ballOneRadius + ballTwoRadius) - normalMagnitude;



		XMFLOAT2 overshootCorrection;

		overshootCorrection.x = (-p_ballOne->getDirection().x * overshoot);

		overshootCorrection.y = (-p_ballOne->getDirection().y * overshoot);

		p_ballOne->move(overshootCorrection);



		overshootCorrection.x = (-p_ballTwo->getDirection().x * overshoot);

		overshootCorrection.y = (-p_ballTwo->getDirection().y * overshoot);

		p_ballTwo->move(overshootCorrection);







		//make normal to collision plane a unit vector 

		XMFLOAT2 unitNormal;

		unitNormal.x = normalVector.x / normalMagnitude;

		unitNormal.y = normalVector.y / normalMagnitude;





		//find unit tangent to collision plane

		//since tangent is perpendicular to collision plane we can 

		//get the unit tangent from the unit normal 

		XMFLOAT2 unitTangent;

		unitTangent.x = -unitNormal.y;

		unitTangent.y = unitNormal.x;



	

		//project velocity onto normal and tangent (= decomposing the velocity vector into tangent & normal)

		XMFLOAT2 ball1Velocity;

		ball1Velocity.x = p_ballOne->getDirection().x * p_ballOne->getSpeed();

		ball1Velocity.y = p_ballOne->getDirection().y * p_ballOne->getSpeed();



		float normalSpeed1, tangentSpeed1;

		float xDot, yDot;



		//project velocity onto normal

		xDot = ball1Velocity.x * unitNormal.x;

		yDot = ball1Velocity.y * unitNormal.y;

		normalSpeed1 = xDot + yDot;



		//project velocity onto tangent

		xDot = ball1Velocity.x * unitTangent.x;

		yDot = ball1Velocity.y * unitTangent.y;

		tangentSpeed1 = xDot + yDot;





		//preserve tangent and normal velocities (unlike pool, where normal velocity would be affected from collision)

		XMFLOAT2 newDirection1;

		newDirection1.x =  -(unitNormal.x * normalSpeed1) + (unitTangent.x * tangentSpeed1);

		newDirection1.y = -(unitNormal.y * normalSpeed1) + (unitTangent.y * tangentSpeed1);

		float directionalMagnitude = sqrt((newDirection1.x * newDirection1.x) + (newDirection1.y * newDirection1.y));

		newDirection1.x /= directionalMagnitude;

		newDirection1.y /= directionalMagnitude;

		p_ballOne->setDirection(newDirection1);













		//project velocity onto normal and tangent (= decomposing the velocity vector into tangent & normal)

		XMFLOAT2 ball2Velocity;

		ball2Velocity.x = p_ballTwo->getDirection().x * p_ballTwo->getSpeed();

		ball2Velocity.y = p_ballTwo->getDirection().y * p_ballTwo->getSpeed();



		float normalSpeed2, tangentSpeed2;



		//project velocity onto normal

		xDot = ball2Velocity.x * unitNormal.x;

		yDot = ball2Velocity.y * unitNormal.y;

		normalSpeed2 = xDot + yDot;



		//project velocity onto tangent

		xDot = ball2Velocity.x * unitTangent.x;

		yDot = ball2Velocity.y * unitTangent.y;

		tangentSpeed2 = xDot + yDot;





		//preserve tangent and normal velocities (unlike pool, where normal velocity would be affected from collision)

		XMFLOAT2 newDirection2;

		newDirection2.x =  (unitNormal.x * normalSpeed1) + (unitTangent.x * tangentSpeed2);

		newDirection2.y = (unitNormal.y * normalSpeed1) + (unitTangent.y * tangentSpeed2);

		directionalMagnitude = sqrt((newDirection2.x * newDirection2.x) + (newDirection2.y * newDirection2.y));

		newDirection2.x /= directionalMagnitude;

		newDirection2.y /= directionalMagnitude;





		p_ballTwo->setDirection(newDirection2);

	

	}



}





void PongPrototype::bounceBallOffWall(Ball* &p_ball)

{

	//bool markedForDeletion = false;



	XMFLOAT2 direction = p_ball->getDirection();

	floatRect region = p_ball->getHitRegion()->getRegion();

	

	//hit left or right? adjust overshoot and flip x direction

	if(region.left <= 0)

	{

		direction.x = -direction.x;

	}



	if(region.right >= SOLIPSIST.getWindowWidth())

	{

		direction.x = -direction.x;

	}



	//hit top or bottom? adjust overshoot and flip y direction + check scoring conditions

	if(region.bottom <= 0)

	{

		//player ball bounces of bottom, otherwise score

		if(p_ball->isFriendly())

			direction.y = -direction.y;

		//else //ball wasn't friendly, score ball

		//{

		//	m_enemyScore++;



		//	markedForDeletion = true;

		//}

	}

	if(region.top >= SOLIPSIST.getWindowHeight())

	{

		/*if(p_ball->isFriendly())

		{

			m_playerScore++;



			markedForDeletion = true;

		}*/

		if(!p_ball->isFriendly())

		{

			direction.y = -direction.y;

		}

	}



	//change direction

	p_ball->setDirection(direction);



	//if(markedForDeletion)

	//{

	//	//TODO: let pass pass through hitregion before deleting

	//	delete p_ball;

	//	p_ball = 0;

	//}

}





//check which balls are in the score zone, remove them and mark up the score

void PongPrototype::removeOvershotBalls()

{

	m_playerScore += m_pHumanPlayer->removeOvershotBalls(m_pParentProject->getWindowHeight() - 20);

	m_enemyScore += m_pEnemyPlayer->removeOvershotBalls(20);

}



//this function is only called when a collision is already detected, so 

//we just have to check which side of the paddle was hit

void PongPrototype::bounceBallOffPaddle(Ball* p_ball, Paddle* p_paddle)

{



	//these boolean are used to determine which part of the brick the ball hit

	bool top	= false;

	bool bottom = false;

	bool left	= false;

	bool right	= false;



	//these floats are used to determine have far the "overshoot" is (that is, how deep one hitregion penetrated into another 

	// - we need this value to make sure things don't get stuck to each other when a collision has occured)

	float ballRadius = p_ball->getHitRegion()->getRegionWidth() / 2;

	float paddleWidth = p_paddle->getHitRegion()->getRegionWidth();

	float paddleHeight = p_paddle->getHitRegion()->getRegionHeight();



	XMFLOAT2 overshootNudge;

	overshootNudge.x = 0.0f;

	overshootNudge.y = 0.0f;





	//centerpoints of colliding objects

	XMFLOAT2 paddlePosition = p_paddle->getPosition();

	XMFLOAT2 ballPosition = p_ball->getPosition();



	//direction of ball after hitting paddle (we "flip" these values)

	XMFLOAT2 ballDirectionPrime;

	ballDirectionPrime.x = p_ball->getDirection().x;

	ballDirectionPrime.y = p_ball->getDirection().y; 



	//distance of the impact from the centrepoint of the brick

	// x > 0 = ball is on right side of brick centre

	// x < 0 = ball is on left side of brick centre

	// y > 0 = ball is above brick centre

	// y < 0 = ball is below brick centre

	XMFLOAT2 impactDistance;

	impactDistance.x =  ballPosition.x - paddlePosition.x;

	impactDistance.y =  ballPosition.y - paddlePosition.y;

	

	if(impactDistance.x > 0)

		right = true;



	if(impactDistance.x < 0)

		left = true;



	if(impactDistance.y > 0)

		top = true;



	if(impactDistance.y < 0)

		bottom = true;





	float paddleWidthHalved = paddleWidth/2;

	float paddleHeightHalved = paddleHeight/2;



	if(left) //impact distance is a negative number (x < 0 -> left) 

	{

			

		//if the centre of the ball isn't positioned past the left wall of the brick we can assume it's a top or bottom hit

		if((impactDistance.x + paddleWidthHalved) > 0)

			left = false;

	}



	if(right) //impact distance is a positive number (x > 0 -> right) 

	{

		if((impactDistance.x - paddleWidthHalved) < 0)

			right = false;

	}



	if(bottom) //distance is negative (y < 0 -> bottom)

	{

		if((impactDistance.y + paddleHeightHalved) > 0)

			bottom = false;

	}



	if(top)

	{

		if((impactDistance.y - paddleHeightHalved) < 0)

			top = false;

	}

		



	if(top || bottom)

	{

		ballDirectionPrime.y *= -1;

		float yNudge = 0.0f;

		

		if(top)

		   yNudge = (paddleHeightHalved + ballRadius) - impactDistance.y;

		

		if(bottom)

		   yNudge = (paddleHeightHalved + ballRadius + impactDistance.y) * -1;



		

		if(yNudge < 0)

			overshootNudge.y = floor(yNudge);

		if(yNudge > 0)

			overshootNudge.y = ceil(yNudge);

		

	}



	if(left || right)

	{

		ballDirectionPrime.x *= -1;

		float xNudge = 0.0f;



		//x-nudge only for hit on the sides

		if(right && !(top || bottom))

			xNudge = (paddleWidthHalved + ballRadius) - impactDistance.x;

		if(left && !(top ||bottom))

			xNudge =  (impactDistance.x + paddleWidthHalved + ballRadius) * -1;





		if(xNudge < 0)

			overshootNudge.x = floor(xNudge);

		if(xNudge > 0)

			overshootNudge.x = ceil(xNudge);

		

	}



		

	Paddle* AIPaddle = m_pEnemyPlayer->getPaddle();

	Paddle* humanPaddle = m_pHumanPlayer->getPaddle();





	if(p_ball->isFriendly() && p_paddle == AIPaddle)

	{

		//remove reference to ball from player vector

		m_pHumanPlayer->popBall(p_ball);

		p_ball->setFriendly(false);

		XMFLOAT2 position;

		position.x = p_ball->getPosition().x;

		position.y = p_ball->getPosition().y;

		p_ball->cleanup();

		p_ball->initialize(SOLIPSIST.getGraphics(),  _T("Graphics/Sprites/enemyBall.dds"));

		p_ball->move(position);

		m_pEnemyPlayer->pushBall(p_ball);



	}



	if(!(p_ball->isFriendly()) && p_paddle == humanPaddle)

	{

		//remove reference to ball from enemy vector

		m_pEnemyPlayer->popBall(p_ball);

		p_ball->setFriendly(true);

		XMFLOAT2 position;

		position.x = p_ball->getPosition().x;

		position.y = p_ball->getPosition().y;



		p_ball->cleanup();

		p_ball->initialize(SOLIPSIST.getGraphics(),  _T("Graphics/Sprites/playerBall.dds"));

		p_ball->move(position);

		m_pHumanPlayer->pushBall(p_ball);

	}





	p_ball->move(overshootNudge);

	p_ball->setDirection(ballDirectionPrime);



}





//TODO: dit heeft eigenlijk geen aparte functie nodig

void PongPrototype::bounceBallOffBrick(PowerupBrick* p_brick, Ball* p_ball)

{

	//these boolean are used to determine which part of the brick the ball hit

	bool top	= false;

	bool bottom = false;

	bool left	= false;

	bool right	= false;



	//these floats are used to determine have far the "overshoot" is (that is, how deep one hitregion penetrated into another 

	// - we need this value to make sure things don't get stuck to each other when a collision has occured)

	float ballRadius = p_ball->getHitRegion()->getRegionWidth() / 2;

	float brickWidth = p_brick->getHitRegion()->getRegionWidth();

	float brickHeight = p_brick->getHitRegion()->getRegionHeight();



	XMFLOAT2 overshootNudge;

	overshootNudge.x = 0.0f;

	overshootNudge.y = 0.0f;





	//centerpoints of colliding objects

	XMFLOAT2 brickPosition = p_brick->getPosition();

	XMFLOAT2 ballPosition = p_ball->getPosition();



	//direction of ball after hitting paddle (we "flip" these values)

	XMFLOAT2 ballDirectionPrime;

	ballDirectionPrime.x = p_ball->getDirection().x;

	ballDirectionPrime.y = p_ball->getDirection().y; 



	//distance of the impact from the centrepoint of the brick

	// x > 0 = ball is on right side of brick centre

	// x < 0 = ball is on left side of brick centre

	// y > 0 = ball is above brick centre

	// y < 0 = ball is below brick centre

	XMFLOAT2 impactDistance;

	impactDistance.x =  (ballPosition.x - brickPosition.x);

	impactDistance.y =  ballPosition.y - brickPosition.y;

	

	if(impactDistance.x > 0)

		right = true;



	if(impactDistance.x < 0)

		left = true;



	if(impactDistance.y > 0)

		top = true;



	if(impactDistance.y < 0)

		bottom = true;





	float brickWidthHalved = brickWidth/2;

	float brickHeightHalved = brickHeight/2;



	if(left) //impact distance is a negative number (x < 0 -> left) 

	{

			

		//if the centre of the ball isn't positioned past the left wall of the brick we can assume it's a top or bottom hit

		if((impactDistance.x + brickWidthHalved) > 0)

			left = false;

	}



	if(right) //impact distance is a positive number (x > 0 -> right) 

	{

		if((impactDistance.x - brickWidthHalved) < 0)

			right = false;

	}



	if(bottom) //distance is negative (y < 0 -> bottom)

	{

		if((impactDistance.y + brickHeightHalved) > 0)

			bottom = false;

	}



	if(top)

	{

		if((impactDistance.y - brickHeightHalved) < 0)

			top = false;

	}

		



	if(top || bottom)

	{

		ballDirectionPrime.y *= -1;

		float yNudge = 0.0f;

		

		if(top)

		   yNudge = (brickHeightHalved + ballRadius) - impactDistance.y;

		

		if(bottom)

		   yNudge = (brickHeightHalved + ballRadius + impactDistance.y) * -1;



		

		if(yNudge < 0)

			overshootNudge.y = floor(yNudge);

		if(yNudge > 0)

			overshootNudge.y = ceil(yNudge);

		

	}



	if(left || right)

	{

		ballDirectionPrime.x *= -1;

		float xNudge = 0.0f;



		//x-nudge only for hit on the sides

		if(right && !(top || bottom))

			xNudge = (brickWidthHalved + ballRadius) - impactDistance.x;

		if(left && !(top ||bottom))

			xNudge =  (impactDistance.x + brickWidthHalved + ballRadius) * -1;





		if(xNudge < 0)

			overshootNudge.x = floor(xNudge);

		if(xNudge > 0)

			overshootNudge.x = ceil(xNudge);

		

	}





	p_ball->move(overshootNudge);

	p_ball->setDirection(ballDirectionPrime);

	p_brick->decreaseHitCounter();

}











//The purpose of this function is to keep the paddle within the confines of the WIN32 window 

//and prevent the player from moving his paddle out of sight

void PongPrototype::correctPaddleOverschoot(Paddle* p_paddle)

{

	XMFLOAT2 offset;

	offset.x = 0.0f;

	offset.y = 0.0f;



	int windowWidth = SOLIPSIST.getWindow()->getWidth();

	int windowHeight = SOLIPSIST.getWindow()->getHeight();

	floatRect region = p_paddle->getHitRegion()->getRegion();





	float margin = 0.4f; 

	//store overshoot corrections

	if(region.left < 0)

		offset.x -= (region.left - margin); //subtract because region.left is a negative value



	if(region.bottom < 0)

		offset.y -= (region.bottom - margin); //same here, subtract because it's a negative value



	if(region.right > windowWidth)

		offset.x -= (region.right - windowWidth) - margin; 

	

	if(region.top > windowHeight)

		offset.y -= (region.top - windowHeight) - margin;





	p_paddle->move(offset);

	

	XMFLOAT2 nullDirection;

	nullDirection.x = 0.0f;

	nullDirection.y = 0.0f;



	p_paddle->setDirection(nullDirection);



}







//check collision against edges of window 

bool PongPrototype::checkBorderCollision(HitRegion* p_region)

{	

	bool collision = false;

	floatRect rect = p_region->getRegion(); //retrieve the location of the hitregion (HitRegion is a wrapper for floatRect)



	//check the border of the map and adjust any overshoots

	if(	rect.bottom <= 0 || rect.top >= SOLIPSIST.getWindow()->getHeight() 

		|| rect.left <= 0 || rect.right >= SOLIPSIST.getWindow()->getWidth())

		collision = true;

	

	return collision;

}
Ugh - that is alot of ugly code just for bouncing a bunch of balls and sticks around.
So, to make a long story short I've decided to kill project solipsist (yes my engine had a name that snooty) and decided to remake the game in SFML.

Don't get me wrong - I'm happy I did it because I learned a ton of stuff BUT:
1) I would like the game to be finished sometime before 2020
2) I would like a modicum of portability
3) I would like to see the inner workings of a properly coded framework
4) the prospect of clean code appeals to me
5) I'm a sucker for reputation points and am going to blog about making this game (and maybe refactoring solipsist).


So yesterday I spent the whole day following this SFML tutorial and have gotten up to this point:

Attached Image


...and now I'm about to work on the collision detection. This is where my code will being to diverge since my paddles move up and down and the player will have multiple balls bouncing around (heh heh again) .

Obviously I'm hoping to avoid the messy code you saw earlier - that's why I'm currently teaching myself trigonometry - if you want to do the same thing I suggest you check out udacity or khan academy.



I'll try to post code and explanations as new things are added. Hopefully newbies can follow along and learn a thing or two.
I didn't do that for this post since it would pretty much be a rip off from the tutorial I posted a link to.

Also, since I am quite busy some patience will be required - Thanks for reading!




September 2014 »

S M T W T F S
  1 23456
78910111213
14151617181920
21222324252627
282930    
PARTNERS