Category Archives: Game Development Series

XBOX 360 Controller Input with C++ using XInput.h API

The XBOX 360 has become one of the most popular game consoles in the world, for the past years. Game developers nowadays, develop games for both Playstation 3 and XBOX 360. In this short tutorial and articles, I decided to cover the XBOX 360 controller, in addition, also how to implement your own class with C++ and use the XInput.h API.

The XBOX 360 Controller Layout and Buttons

The XBOX 360 Controller layout and buttons (see the image below), the controller has 2x analog sticks, 2x analog triggers, 11x digital buttons and one digital D-Pad.

As any hardware, the XBOX 360 controller has constant hexadecimal values, these are predefined of course.

//
// Constants for gamepad buttons
//
#define XINPUT_GAMEPAD_DPAD_UP          0x0001
#define XINPUT_GAMEPAD_DPAD_DOWN        0x0002
#define XINPUT_GAMEPAD_DPAD_LEFT        0x0004
#define XINPUT_GAMEPAD_DPAD_RIGHT       0x0008
#define XINPUT_GAMEPAD_START            0x0010
#define XINPUT_GAMEPAD_BACK             0x0020
#define XINPUT_GAMEPAD_LEFT_THUMB       0x0040
#define XINPUT_GAMEPAD_RIGHT_THUMB      0x0080
#define XINPUT_GAMEPAD_LEFT_SHOULDER    0x0100
#define XINPUT_GAMEPAD_RIGHT_SHOULDER   0x0200
#define XINPUT_GAMEPAD_A                0x1000
#define XINPUT_GAMEPAD_B                0x2000
#define XINPUT_GAMEPAD_X                0x4000
#define XINPUT_GAMEPAD_Y                0x8000

The constants can be found in Xinput.h (C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\Xinput.h), the Xinput.h is a C/C++ header file with the API code, or function declarations, variables and constant values. By including the Xinput.h in our code we can write custom functions that utilize the API to communicate with the XBOX 360 Wireless Controller. In order for you to be able to use the Xinput.h you’ll have to install Windows SDK 7.1.

Time to write the code

The very first function we will program in Win32 C++ is called: IsXBOXControlConnected(); and this function will be a boolean, this is very obvious and straight forward.

bool IsXBOXControlConnected()
{
   //Invoke the memset(); function to zero the XBOX_CONTROLLER_State. 
   memset(&XBOX_CONTROLLER_State, 0, sizeof(XINPUT_STATE)); 

   //We store the XInputGetState value inside result, note that result is a DWORD which is a typedef unsigned long. 
   DWORD result = XInputGetState(XBOX_CONTROLLER_NUM, &XBOX_CONTROLLER_State); 

   //Check if the controller is disconnected using the Ternary Operator. 
   return  result == ERROR_DEVICE_NOT_CONNECTED ? false : true;  
}

It is easy to verify whether our class and function works, we just make a pointer of the XBOXController* and invoke the constructor with the new keyword to allocate memory and set memory address for it.

#include <Windows.h>
#include "XBOXController.h"
#include <iostream>

using namespace std; 

void main()
{
	XBOXController* xctrl = new XBOXController(0); 
	if(xctrl->IsXBOXControlConnected())
	      cout << "The XBOX 360 controller is connected!" << endl; 
	else 
	      cout << "The XBOX 360 controller is disconnected!\nPlease check your XBOX 360 controller again!" << endl; 

	cin.get(); 
}

When we execute the above code in main.cpp we either see “The XBOX 360 Controller is connected!” or “The XBOX 360 controller is disconnected! Please check your controller again!”, see the command screenshot below:

Awesome, let’s move onto the Vibration(); function. According to the MSDN Documentation, the vibration accepts values between 0 and 65,535. Let’s implement the Vibration(); function which is going to be a void, because it will only perform the code inside, and not return something.

void XBOXController::Vibrate(float left, float right)
{
    XINPUT_VIBRATION vibration; 

    //Invoke memset to zero out the XINPUT_VIBRATION. 
    memset(&vibration, 0, sizeof(XINPUT_VIBRATION)); 

    /*
       According to MSDN Documentation on this, 
       speed of the left or right motor. Valid values are 
       in the range 0 to 65,535. Zero signifies no motor 
       use; 65,535 signifies 100 percent motor use.
    */

    vibration.wLeftMotorSpeed = (int)(left*65535.0f); 
    vibration.wRightMotorSpeed = (int)(right*65535.0f); 

    //Vibrate the controller 
    XInputSetState(XBOX_CONTROLLER_NUM, &vibration); 
}

Now, one final, function we should implement is the GetState(); function which allows us to check if the player pressed A or B etc on the XBOX controller. This one is simple to implement.

XINPUT_STATE XBOXController::GetState()
{
    memset(&XBOX_CONTROLLER_State, 0, sizeof(XINPUT_STATE)); 
    XInputGetState(XBOX_CONTROLLER_NUM, &XBOX_CONTROLLER_State); 
    return XBOX_CONTROLLER_State; 
}

Now we’re done with this simple example entirely written in C++ Win32, so how should we use this code in our main.cpp, easy, I have added the code below.

#include <Windows.h>
#include "XBOXController.h"
#include <iostream>

using namespace std; 

void main()
{
   XBOXController* player1 = new XBOXController(1); 

   system("color 0a"); 

    cout << "Instructions:\n";
    cout << "Press [A] to vibrate left only\n";
    cout << "Press [B] to vibrate right only\n";
    cout << "Press [BACK] to exit\n";          

    while(true){ 	
        if(player1->IsXBOXControlConnected()){
	    if(player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_A)
		{  player1->Vibrate(65535, 0); }

		if(player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_B)
		{ player1->Vibrate(0, 65535); }

		if(player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_BACK)
		{ break; }
	}
	else{

		cout << "\nERROR! PLAYER 1 - XBOX 360 Controller Not Found!\n";
                cout << "Press Any Key To Exit.";
                cin.get();
                break;
	}

	delete player1; 
     }
}

Finally, let’s run this code, in my case I have no wireless USB adapter or cable to connect the XBOX 360 controller to my laptop, therefore, I receive the error because it returns false when checking for XBOX controller connection status.


 

Wrapping up

I’m done with this, for now. I think it’s fun to play around with this, since it’s so easy to use the provided API. In addition, I think this code can be further expanded, meaning that we can do more checks and add more functionality. However, most of this code is not elegant or perfect, but it should work, the main idea here is for you to understand the concept, the rest is up to you.
 
But for now, happy coding!
 

First Person Shooter Cameras

In this article I’ll be covering the concepts and what level of math knowledge is required for making a First-Person Shooter (FPS) Camera in games. So let’s get started with some common concepts: pitch, yaw, and roll. Pitch is when the player moves the camera up and down. Yaw is when the player moves the camera from left to right and respectively. And finally Roll is when the player tilts the camera from left to right and respectively,  this rotation usually occurs around the Z-axis.

Camera movements using the computer mouse (Pitch, Yaw and Roll)

 

The FPS Camera functions

In FPS games, the is camera required to do the following:

  • Move forward and backward (Using the W or S keys on the keyboard)
  • Strafe Left or Right (Using the A or D keys on the keyboard)
  • Jump (Using the [space] key on the keyboard)
  • Look around (Using the mouse):
    Pitch (Look up and down), Yaw (Look left or right) and Roll (Tilt left or right)

 

Camera movements using the computer keyboard

Camera movements using the computer keyboard

 

Advanced Mathematics knowledge is required to make an FPS camera

As you already know, all kind of programming will require some mathematics knowledge. However, game programming is a challenging level of programming, and the mathematics required here, goes usually beyond what the average person knows, with other words even the math becomes challenging in the way it is required to be used. Here’s how the axis are used for an FPS camera:

Vectors used to describe the position and orientation of the camera in the world

 

The picture above describes the Euler Angles, and are based on Euler’s Rotation Theorem that any rotation can be described using three angles (X, Y, Z). Another mathematics formula or method to be applied here is Matrix, no I am not referring to Matrix the movie. The matrix in game development is often described as view matrix.

The Matrix

 

In addition to what has been covered so far, you also need the following skills: Geometry, Trigonometry (You only need: sin and cos), Vectors, Matrices, 2D and 3D transforms, Projections, and Transformations between coordinate systems. However, please note that I cannot teach you math here, but I will later post a complete tutorial on how to make your own FPS camera with C++ and we will either be using OpenGL or DirectX.

 

References:
Weisstein, Eric W.
“Euler Angles.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/EulerAngles.html
Weisstein, Eric W.
“Euler’s Rotation Theorem.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/EulersRotationTheorem.html
Weisstein, Eric W.
“Matrix.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/Matrix.html
Weisstein, Eric W.
“Trigonometry.” From MathWorld–A Wolfram Web Resource.
http://mathworld.wolfram.com/Trigonometry.html
Weisstein, Eric W.
“Sine.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/Sine.html
Weisstein, Eric W.
“Cosine.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/Cosine.html
Weisstein, Eric W.
“Geometry.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/Geometry.html
Vector: http://content.gpwiki.org/index.php/Vector

 

How to make games

In this article I am going to be covering the process behind making games (or Game Development). And I am also going to cover some additional details, like what knowledge is required, what math skills are required and much more.

What is a game?

Wikipedia defines a game as:

“…is structured playing, usually undertaken for enjoyment and sometimes used as an educational tool.”

My own basic definition:

“A game is more than an activity with a score, a game provides entertainment with an excellent goal to play and complete it.”

Traditionally and generally a game should contain these three basic components:

  • Interactive element(s)  (Objects, which you control  in the game e.g. character)
  • Challenge (The game must have some challenge, it shouldn’t be easy to complete)
  • A goal (A story + ending or Best Game Stats)

It is very obvious that a game must be interactive, and the game must involve some kind of challenge (e.g. a boss with higher level if RPG) and the game must have a predefined goal which the player really wants to achieve.

I’ll give you an example; let’s have a closer look at FlatOut 2™.

 

 

In FlatOut 2™ the interactive component is the car you drive, since you control the speed and control the movement (you turn right or left). The goal in this game is to win as many races as possible, and the challenge is that you have competition all the other cars are programmed and controlled by the computer (i.e. bots). The bots don’t often do mistakes, and this poses a challenge on the player.

The Components of a Game (Basic Level)

In order for us to make a game we actually need to understand the components that make up a game, I’ll explain this on a basic level.

  • The rules of the game (i.e. the basic engine and default choices of the game characters includes more)
  • The Graphics
  • The Sound and additional media

 

The Rules of the Game

The rules are very basic to set, OK, let me explain. I love being a programmer; I love this world and field, because as a programmer you get to be the god of games and software programs. For example, I can set the default rules for any game I make, I can set default points, and Health Points (HP) for any game character, and I get to decide how the character shall look, what skills it shall have etc. wow, this is really working as a god of your own creations.

 

The Graphics

Graphics is really the component that captures the attention of the player. Graphics are very important in games, nobody wants to buy a Text-Based Game nowadays, because, our computers are much more powerful these days, and our PCs allow us to play games with better graphics. Most graphics in games are composed by two distinct types:

  • Sprites
  • Tiles

 

Sprites usually consist of anything that can be moved (e.g. the super Mario character).

Tiles usually make up everything else, the rest of the graphics in the game, or at least other objects which usually are fixed and cannot be move unless blown up by a gun.

 

The Sound and additional media

The sound is very important component in the game, it really gives that little extra feeling, OK, let me explain, if you want to the cinema and you paid for Man In Black 3 (or MIB3) they cinema played the movie for you, but without sound, how would that feel? Exactly, the exact same feeling appears when you play games without sound. However, the sound in games comes in the form of background music and sound-effects, and sometimes additional media as a voice from another game character.

Here’s a clip of the Super Mario Bros (Listen to the sound):

The following article in PDF provides additional details on how early game sound designers engineered their work, In the Loop: Creativity and Constraint in 8-bit Video Game Audio

How to make a game?

OK, so I think we now understand some of the basic components that make up a game. However, now it’s time to make our own game. But in order for us to make a game, we need to check our skills; a game developer must know and understand computer programming. However, do not worry; it is possible to make a game either way, except that one path will differ from another.

 

Implementing the actual rules of the game

Remember the god job? Kidding, but it is almost like that in the world of game development. However, the rules of a game are often best expressed as a sequence of logical operations and condition. Implementing this is easy, but it also depends on the developer, does he/she understand computer programming. It is important to know programming in order to implement the rules of the game.

 

The Choice of Target Platform

There exist a few platforms that are very popular; I think it is important to make target-platform choices. Before we actually get into the details of how to actually make a game, it is important to make some decisions or make a choice (BTW, you can always change your mind). I personally would go for the target-platform that provides very high exposure.

 

 

If I make a game, I want as many people to play it, so they can send me positive/negative feedback with additional suggestions, that way I can improve the game. High exposure allows me to make two editions of the game, for example, the free edition includes a number of features and stuff, while the paid edition includes extra stuff, and gives the player access to new stuff.

 

The Technical Fundamentals of How a Game Works

Player input (Keyboard and Mouse): The player input is really the main force in the game; almost everything the game logic (Game Engine) does is to respond to player inputs in different ways. The input usually comes from Keyboard and the Mouse; however, there are other input devices like a hand control or joystick.

Collision Detection (Objects): Performing collision detection test between two objects can be a very complicated task; it involves math skills and programming including graphics. Here’s an example with two Spheres:


Figure 1: r1 and r2 does now mean r ^ 1 or 2 it simply means radius 1 and 2.

This is called: Bounding Spheres. To determining if two spheres collide is pretty simple, but can be complicated. However, to gain a quick understanding of this problem, let us take a look at what happens when two spheres are touching each other. OK, as we can see in this Figure 1, the radius (r) of each sphere including the definition of the distance for its center to the opposite sphere. Given this information, the distance between the centers would be equal to = r1 + r2. If the distance is greater, the two spheres would not touch each other, but, if the distance isn’t greater, then the spheres would intersect.

Artificial Intelligence: AI can be done; however, it isn’t real AI since the game characters (the creatures or cars in the game not controlled by the player but by the PC, a.k.a. bots) have predefined operations e.g. walk, drive, attack etc. While AI in theory is described as “intelligence” that can learn and do different things.

Camera: The Camera in games works much like a movie camera (like Hollywood). The camera governs what we see on the screen. The game world is often much larger than the screen, so the camera allows us to see the part where we are active in the game. Screen bounds, if the player goes outside the bounds of the screen, the camera will move so we can still see the player.

 

I do not know computer programming (give me directions)

If you do not know computer programming, I will help you, but, with directions, since I cannot teach you programming over Internet. You can make games using C#, C/C++, Java, Ruby or almost any other programming language.

For C# See this:

http://msdn.microsoft.com/en-us/vstudio/hh341490.aspx

http://msdn.microsoft.com/en-us/library/a72418yk.aspx

http://www.csharp-station.com/tutorials/lesson01.aspx

For C/C++ See this: http://www.cprogramming.com/

For a basic library, and since you are a beginner in programming, well, once you learned programming and Object Oriented Programming (OOP), then download Allegro, via this site: http://alleg.sourceforge.net//index.html

 

I know computer programming (feed me with additional tips)

If you already know and understand computer programming, and know OOP, then I’ll provide you with additional tips.

DirectX: http://msdn.microsoft.com/en-us/directx/aa937788.aspx

or OpenGL: http://www.opengl.org/

SFML: http://www.sfml-dev.org/

Additional resources:

DirectX Tutorials: http://directxtutorial.com/Tutorial9/B-Direct3DBasics/dx9B1.aspx

OpenGL Getting Started: http://www.opengl.org/wiki/Getting_Started

Getting Started with OpenGL:

http://www.codeproject.com/Articles/2215/Getting-Started-With-OpenGL

Getting Started with SFML:
http://www.sfml-dev.org/tutorials/1.3/start-vc.php

 

Make a prototype

Once you have a game idea, you should try to draw it on paper, this way you can test your idea, and you can make a prototype of the game e.g. a beta version. Here’s an article about paper-based prototypes: Quick, Easy, and Effective Paper Prototypes. Here is another article, very useful: Prototyping: You’re (Probably) Doing It Wrong.

 

How do you make a good game?

This process is the most difficult part of all. For example, you’ve got your game idea, and you’ve made a prototype, but how do you know if the game is good?

Well, once you’ve been working on a game for a while, it does get difficult to tell, if what you’ve been making a game that is fun. The main reason behind the difficulty; is that being constantly exposed to every minute of working on the game, does not really give you the actual minute to play and enjoy, for example: when you buy a game you will play it right? But when you are building a game, things get different; you spend more time focusing on the project plan than playing the actual game.

The next step is to let as many people as possible, to play your game and let you know what they think about it. Collect as much feedback as possible, and try to remember one thing: “every single piece of deeply constructive negative feedback IS correct”. The people that take the time out to tell you, what they don’t like are right. Of course, there are things they might not like, which you still want the game to have, however, that cannot be changed, unless you really have to.

 

Best of luck!

Well, I have simply covered almost everything in Game Development, or at least a quite large part. And I’ve also covered everything from concept to the actual implementation of the game. Making a game is not an easy process, as you might know by now. It requires time, so you have to allocate time, and be patient. The best advice I can give you, never give up and always try, work hard, talk to people that are in the business, and ask your programming teacher or ask me.

 

Sources:
Screenshot FlatOut 2 (http://screenshots.teamxbox.com/screen/50011/FlatOut-2/)