**1**

# Arkanong part 3: Vector reflector

Posted by

**molehill mountaineer**, 18 November 2013 · 547 viewsc++ sfml pong breakout arkanong vector reflection

Yesterday I posted a few snippets of code to show how game objects can be kept within the confines of a client window. Because my game ball stores the direction it is heading in as an angle, the quick and dirty way to bounce it back was to add or subtract 90°.

This only works if you can guarantee that the ball will be coming in at one of four angles (45°, 135°, 225°, 315°) - otherwise the new angle doesn't look natural. This method of adding or subtracting 90° is essentially a way of doing vector reflection without doing any actual calculations (not counting the adding or subtracting of course).

That's nice if you're going for that authentic retro pong feeling, but I'd like the game to feel a bit more like pool. Before you read this code I recommend you check out understanding vector reflections visually to get a grasp of what's going on and stack exchange to see the formula I'll be using.

A 'unit normal vector' is a vector perpendicular to a surface (= normal) which has been normalized (= having a magnitude of one).

Thus, finding the normals of the four sides of the window is easy:

left side: (1, 0)

right side: (-1, 0)

top side: (1, 0) //remember that y grows downwards

bottom side: (-1, 0)

If all of this seems like gibberish to you I strongly recommend you brush up on your maths. It may seem like a chore, but a little mathematics can go a very long way. Vectors, matrices, trigonometry - all of this will pop up frequently in the course of developing a game. I used to hate doing math until I started programming, now I get to use it to bounce balls around on the screen which is much more rewarding than writing a number down on a piece of paper. check out khan academy or udacity if you're looking to learn.

Ok, so this is what the new collision response looks like:

The next step is to feed the data into the reflection formula - this should make sense if you clicked the links in the beginning of this post.

Now that we have the vector representing the new direction we use the function atan (= arctan = trigonometry!) to get the angle of the vector in radians. I find degrees much easier to work with so I convert it by multiplying with (180.0f/3.1415926).

Cool, now I can bounce the ball at any angle I damn well please - let's put in some code to play around with the reflection.

in Game::Tick()

The code pertaining to the game is in the directory "pong_rework". You will find the collision detection/response code in the ObjectManager class.

This only works if you can guarantee that the ball will be coming in at one of four angles (45°, 135°, 225°, 315°) - otherwise the new angle doesn't look natural. This method of adding or subtracting 90° is essentially a way of doing vector reflection without doing any actual calculations (not counting the adding or subtracting of course).

That's nice if you're going for that authentic retro pong feeling, but I'd like the game to feel a bit more like pool. Before you read this code I recommend you check out understanding vector reflections visually to get a grasp of what's going on and stack exchange to see the formula I'll be using.

A 'unit normal vector' is a vector perpendicular to a surface (= normal) which has been normalized (= having a magnitude of one).

Thus, finding the normals of the four sides of the window is easy:

left side: (1, 0)

right side: (-1, 0)

top side: (1, 0) //remember that y grows downwards

bottom side: (-1, 0)

If all of this seems like gibberish to you I strongly recommend you brush up on your maths. It may seem like a chore, but a little mathematics can go a very long way. Vectors, matrices, trigonometry - all of this will pop up frequently in the course of developing a game. I used to hate doing math until I started programming, now I get to use it to bounce balls around on the screen which is much more rewarding than writing a number down on a piece of paper. check out khan academy or udacity if you're looking to learn.

Ok, so this is what the new collision response looks like:

//bounce ball off sides if(collisionDetected) { object->getSprite().move(overshootCorrection); //correct overshoot sf::Vector2f ballVector = ((GameBall*)object)->getVelocities(); float dotProduct = (ballVector.x * collisionNormal.x) + (ballVector.y * collisionNormal.y); sf::Vector2f reflectionVector = ballVector - 2*dotProduct*collisionNormal; //call arctan to get angle back from vector and convert to degrees float newAngle = std::atan2f(-1 * reflectionVector.y,reflectionVector.x) * (180.0f/3.1415926); //we will assume all spherical objects are gameballs (for now) ((GameBall*)object)->setAngle(newAngle); }Since I am working with an angle and speed (and the formula reflects a vector) the first thing I do is call getVelocities() to get the movement vector. GetVelocities() is the function I posted yesterday which 'divides' the speed into and offset on the x and y axis (i.e. a vector).

The next step is to feed the data into the reflection formula - this should make sense if you clicked the links in the beginning of this post.

Now that we have the vector representing the new direction we use the function atan (= arctan = trigonometry!) to get the angle of the vector in radians. I find degrees much easier to work with so I convert it by multiplying with (180.0f/3.1415926).

Cool, now I can bounce the ball at any angle I damn well please - let's put in some code to play around with the reflection.

void ObjectManager::spawnBall(sf::Vector2f& destination, bool playerBall) { sf::Vector2f source; if(playerBall) { //ball spawns at player location source = m_objects.find("PlayerPaddle")->second->getPosition(); } //TODO: implement spawning ball from enemy paddle when !playerBall //get the vector from player to destination sf::Vector2f vector = destination - source; //determine angle of vector and convert to degrees float angle = std::atan2f(-1*vector.y,vector.x) * (180.0f/3.1415926); //convert to degrees GameBall* newBall = new GameBall(); newBall->setPosition(source.x, source.y - 30); newBall->setAngle(angle); //Find a unique name for the new ball bool uniqueNameFound = false; std::stringstream ss; if(playerBall) ss << "PlayerBall"; else ss << "EnemyBall"; int ballNumber = m_objects.size(); while(!uniqueNameFound) { ss << ballNumber; std::string stringballNumber = ss.str(); if(this->getObject(stringballNumber) == 0) //check if name is free { this->addObject(stringballNumber, newBall); uniqueNameFound = true; } else //name was already taken -> make the number higher and try again { ++ballNumber; } } }This function spawns a ball at the position of the paddle and make it head towards the destination. It is called in Game::Tick() when the mousebutton is released (note that I didn't use mousePressed as this would keep making balls while you're holding down the button. You'd have to have some killer timing to spawn a single ball).

in Game::Tick()

switch(m_currentState) { case IsRunning: [edited for brevity] if(currentEvent.type == sf::Event::MouseButtonReleased) { sf::Vector2f mouseclick; mouseclick.x = sf::Mouse::getPosition(m_mainWindow).x; //x relative to window mouseclick.y = sf::Mouse::getPosition(m_mainWindow).y; //y relative to window m_pObjectManager->spawnBall(mouseclick, true); //spawn player ball }Now we can bounce balls to our heart's content! As always you can check out the project here

The code pertaining to the game is in the directory "pong_rework". You will find the collision detection/response code in the ObjectManager class.