Click here to Skip to main content
15,867,686 members
Articles / Game Development / XBox

Driving Simulation in XNA

Rate me:
Please Sign up or sign in to vote.
4.65/5 (17 votes)
14 Sep 2008CPOL4 min read 123.5K   9.6K   58   22
A Tutorial to develop a driving simulator using XNA Game Studio 2.0
Image 1

Introduction

This is the first instalment of a series of tutorials in which we aim to make a 3D Driving Simulation Game. With every successive tutorial, we will try to make the game cooler by adding new features in graphics, physics and gameplay. The aim of this first tutorial is to simulate a car over an infinitely large plane. I know this is not exactly what we have in the real world. But we will get more realistic in later tutorials. For now, imagine the world as a perfect plane with no obstacles.

Background

This article is not for the absolute beginner. A basic understanding of XNA Game Studio 2.0 is necessary. But If you are a beginner, I would suggest the following:

  1. Download and Install Microsoft Visual C# 2005 Express Edition, its SP1 Update, and XNA Game Studio 2.0. All these can be downloaded free of cost from www.microsoft.com.
  2. Go through the 'XNA Game Studio Documentation', especially the articles 'Your First Game: Microsoft XNA Game Studio in 2D' and 'Going Beyond: XNA Game Studio in 3D'. These tutorials are fairly easy to comprehend.
  3. Go through the Riemer's XNA Tutorial. Reading all the 3 tutorials will give you a very good understanding of XNA. But for now, the first 2 tutorials are sufficient. The concept of Quaternions should be clearly understood.

Reasonable Knowledge of Newtonian Mechanics and Geometry is necessary to understand the formulas.

Using the Code

The application has been divided into three classes Game1, Stuff, Car. The class Stuff represents any material body that can be rendered on the screen. The class Car is a specialization of the Class Stuff which represents a Car. The class Game1 is the main application and uses objects of Stuff and Car.

Let us first understand the class Stuff. If you go through the code, you will see that I have tried to encapsulate everything required to store information of any material body and render it on screen. I am only providing an overview of the member variable and function since the code is fairly straight forward.

  • The members viewMatrix and projectionMatrix are static because they are the same for all renderable objects.
  • The members position and rotation represent the position of the object and its orientation respectively in 3D Space.
  • The member cameraRotation represents the orientation of the camera. Storing this is necessary to achieve the effect of camera delay.
  • The member model represents the 3D Model of the body.
  • The function UpdateCamera updates the viewMatrix according to the position and orientation of car.
  • The function Draw renders the 3D Model on the screen.

Now for the most difficult part - understanding the class Car. There are two concepts at work. The first one is the effect of hitting the accelerator, releasing it, and braking on the cars motion. The second one is how the car turns when the steering is turned left or right.

The first concept. At any instant, the car is in some gear represented by the variable gear. The speed of the vehicle determines the gear. We have the top speed at each gear stored in the variable topSpeeds. The top speed at gear x is also the minimum speed for gear x+1. The acceleration is different at each gear.

C#
public void Accelerate()
{
    free = false;

	if ((gear<7)&&(speed > topSpeeds[gear]))
    {
        gear++;                
    }
    if (gear == 0)
    {
        acceleration = accelerations[1];
    }
    else if (gear < 7)
        acceleration = accelerations[gear];
    else
    {
        gear = 6;
        acceleration = 0;
         speed = topSpeeds[6];
    }
}

Now when the brake is applied, the effect is that a negative acceleration whose magnitude is the acceleration at that gear added to a constant as shown. Here you also have to consider the reverse gear and the maximum speed in reverse.

C#
public void Brake()
{
    free = false;

    if((gear>0)&&speed<=topSpeeds[gear-1])
    {
        gear--;
    }
    if ((gear == 0) && (speed < -maxReverseSpeed))
    {
        acceleration = 0;
        speed = -maxReverseSpeed;
    }
    else
    {
        acceleration = -accelerations[gear]-6.7f;              
    }
}

Also when the accelerator is released, even then a negative acceleration with magnitude same as acceleration at that gear has to be applied. And eventually the car comes at rest.

C#
public void Free()
{
    free = true;

    if ((gear>0)&&(speed < topSpeeds[gear - 1]))
    {
        gear--;
    }
          
    acceleration = - accelerations[gear];         
}

To determine the new position of car after every instant, the following code is placed in the Update method.

C#
float speed = speed + acceleration * time;
float dist = speed * time;
Vector3 addVector = Vector3.Transform(new Vector3(0, 0, -1), rotation);
position += addVector * dist;

To make sure the car eventually comes to a stop when neither accelerator nor brake is pressed, this code is used:

C#
float newSpeed = speed + acceleration * time;
if ((free == true) && (newSpeed * speed <= 0.0f))
{
	gear = 1;
	acceleration = accelerations[gear];
	speed = 0.0f;
}
else
	speed = newSpeed;

Now let us understand how a car turns. When the driver steers left or right, the plane surface makes an angle theta with the body of the car as shown in the figure. Theta should uniformly increase from to 0 to a Maximum Value. Also when the steering is left free theta should eventually become zero. The code for this is as follows:

C#
if (turn == 0)
{
	float newAngle = steerAngle;
	if (steerAngle < 0.0f)
	{
		newAngle = steerAngle + time * steerSpeed;
	}
	else if (steerAngle > 0.0f)
	{
		newAngle = steerAngle - time * steerSpeed;
	}
	if (newAngle * steerAngle < 0.0f)
	{
		steerAngle = 0.0f;
	}
	else
		steerAngle = newAngle;
}
else
{
	if (turn == -1)
	{
		float newAngle = steerAngle - time * steerSpeed;
		if (newAngle < -maxSteerAngle)
		{	
			steerAngle = -maxSteerAngle;
		}
		else
		{
			steerAngle = newAngle;
		}
	}
	else
	{
		float newAngle = steerAngle + time * steerSpeed;
		if (newAngle > maxSteerAngle)
		{
			steerAngle = maxSteerAngle;
		}
		else
		{
			steerAngle = newAngle;
		}
	}                
}

Now that we have understood how the tire turns, let us figure out how the car turns. Look at the figure carefully:

Image 2

You will at once understand what the constants HD,VD and L represent. O is the origin of the 3D Model. We assume that the car will rotate about the point marked "Center Of Turning" with radius r. The value of r can be calculated using trignometry:

C#
float x = (VD / Math.Abs((float)Math.Tan(steerAngle)) + HD / 2);
float r = (float)Math.Sqrt(x * x + L * L);

Now we have the radius. The angle by which the car rotates can be found out and corresponding Quaternion is created.

C#
float theta = speed * time / r;
if (steerAngle < 0.0f)
theta = -theta;
rotation = rotation * Quaternion.CreateFromAxisAngle(new Vector3(0, -1, 0), theta);

New the position of car can be determined as follows:

C#
speed = speed + acceleration * time;
float dist = speed * time;
Vector3 addVector = Vector3.Transform(new Vector3(0, 0, -1), rotation);
position += addVector * dist;

The rest of the code is pretty much straight forward.

I would like to thank my friend, Tarang Bakshi, for his help with the game physics and ideas.

History

  • 14th September, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I am a Software Developer from Hyderabad, India

My MSDN Blog

My Windows Phone Apps

Comments and Discussions

 
GeneralMy vote of 4 Pin
Member 115775762-Apr-15 19:32
Member 115775762-Apr-15 19:32 
GeneralMy vote of 1 Pin
Member 115775762-Apr-15 19:24
Member 115775762-Apr-15 19:24 
QuestionWhere? Pin
zimbob4-Apr-14 2:59
zimbob4-Apr-14 2:59 
QuestionBroken link for source code Pin
Fernando Gonzalez Sanchez31-Dec-13 11:38
Fernando Gonzalez Sanchez31-Dec-13 11:38 
QuestionChange background Pin
DeGenerationX12-May-11 5:51
DeGenerationX12-May-11 5:51 
GeneralNo texture for the car Pin
artem0056-Apr-10 6:32
artem0056-Apr-10 6:32 
GeneralCamera views Pin
Charithmax3-Apr-10 17:57
Charithmax3-Apr-10 17:57 
GeneralRe: Camera views Pin
AmitDey3-Apr-10 19:27
AmitDey3-Apr-10 19:27 
Generalhai i have a query Pin
Lakshmi sravani5-Dec-09 3:09
Lakshmi sravani5-Dec-09 3:09 
Generalcrashed ,cause a file didn't founded Pin
ehsan_kh13-Oct-08 5:40
ehsan_kh13-Oct-08 5:40 
GeneralRe: crashed ,cause a file didn't founded Pin
AmitDey13-Oct-08 7:23
AmitDey13-Oct-08 7:23 
GeneralCan't get the sample to work Pin
yassir hannoun14-Sep-08 10:36
yassir hannoun14-Sep-08 10:36 
GeneralRe: Can't get the sample to work Pin
User 665814-Sep-08 10:59
User 665814-Sep-08 10:59 
GeneralRe: Can't get the sample to work Pin
yassir hannoun14-Sep-08 11:48
yassir hannoun14-Sep-08 11:48 
GeneralRe: Can't get the sample to work Pin
AmitDey14-Sep-08 19:53
AmitDey14-Sep-08 19:53 
Generali try to run, but don't works... Pin
Sergey Alexander Gynech14-Sep-08 10:34
Sergey Alexander Gynech14-Sep-08 10:34 
GeneralRe: i try to run, but don't works... Pin
User 665814-Sep-08 11:02
User 665814-Sep-08 11:02 
JokeOooooo...... Pin
The Cake of Deceit14-Sep-08 9:57
The Cake of Deceit14-Sep-08 9:57 
GeneralRe: Oooooo...... Pin
User 665814-Sep-08 10:02
User 665814-Sep-08 10:02 
GeneralGood article, some suggestions Pin
User 665814-Sep-08 9:41
User 665814-Sep-08 9:41 
GeneralRe: Good article, some suggestions Pin
AmitDey14-Sep-08 19:59
AmitDey14-Sep-08 19:59 
GeneralRe: Good article, some suggestions Pin
AmitDey14-Sep-08 23:48
AmitDey14-Sep-08 23:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.