• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
  • entries
  • comments
  • views

Arkanong part 3: Vector reflector

Sign in to follow this  
Followers 0
molehill mountaineer


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: //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 [color=#b4b4b4]([/color][color=#b5cea8]180.0f[/color][color=#b4b4b4]/[/color][color=#b5cea8]3.1415926[/color][color=#b4b4b4]). [/color]

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.

Sign in to follow this  
Followers 0


There are no comments to display.

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