Program Car Race Game Opengl Source Code

XNA has a starter kit for racing games along the theme of Project Gotham. For a basic top down track game, George Clingerman has 'the road not taken' tutorial which can get you started with tracks and collision. As for a sample with AI, I did find a 2d racing tutorial a long time ago, but I don't remember where:doh:. Twin Cars Game Computer Graphics Project in OpenGL Source Code – 18CSL67. Here you can download the source code Twin Cars Game Computer Graphics Project in OpenGL – 18CSL67 academic mini-project.

Sat, Jun 23, 2012

Previously we introduced our outrun-style racing game, but how do weget started building a pseudo-3d racing game ?

Well, we’re going to need to

  • revise some trigonometry
  • revise basic 3d projection
  • build a game loop
  • load some sprite images
  • build some road geometry
  • render the background
  • render the road
  • render the car
  • enable keyboard support to drive the car

Before we do any of that, lets go off and read Lou’s Pseudo 3d Page -its the main source of information (that I could find) online about how to build a pseudo-3d racing game.

Program car race game opengl source code list

NOTE: Lou’s page doesn’t render well in google chrome - so its best viewed using Firefox or IE

Finished reading Lou’s article ? Great! We’re going to build a variation on his ‘Realistic Hills Using3d-Projected Segments’ approach. We will do it gradually, over the course of the next 4 articles, but wewill start off here with v1, building very simple straight road geometry and projecting it onto our HTML5canvas element.

see it in action here

Some Trigonometry

Before we get down to the implementation, lets use some basic trigonometry to remind ourselves how to projecta point in a 3D world onto a 2D screen.

At its most basic, without getting into vectors and matrices, 3D projection uses a law of similar triangles.If we were to label:

  • h = camera height
  • d = distance from camera to screen
  • z = distance from camera to car
  • y = screen y coordinate

Then we could use the law of similar triangles to calculate

y = h*d/z

as shown in the diagram below:

We could have also drawn a similar diagram from a top-down view instead of a side-on view and derived a similarequation for calculating the screen x coordinate as

x = w*d/z

Where w = half the width of the road (from camera to road edge)

You can see that for both x and y, what we are really doing is scaling by a factor of

d/z

Coordinate Systems

This sounds nice and simple in diagram form, but once you start coding its easy to get a little confused because we havebeen a bit loose in naming our variables and its not clear which represent 3d world coordinates andwhich represent 2d screen coordinates. We’ve also assumed that the camera is at the origin of our world when inreality it will be following our car.

More formally we should be:

  1. translating from world coordinates to camera coordinates
  2. projecting camera coordinates onto a normalized projection plane
  3. scaling the projected coordinates to physical screen (in our case canvas) coordinates

NOTE: in a true 3d system a rotation step would come between steps 1 and 2, but since we’re going to be faking curves we dont need to worry about rotation

Projection

And so we can present our formal projection equations as follows:

  • The translate equations calculate the point relative to the camera
  • The project equations are variations of our ‘law of similar triangles’ above
  • The scale equations take into account the difference between:
    • math - where 0,0 is at the center and the y axis goes up and
    • computers - where 0,0 is at the top-left and the y axis goes down, as shown below:

NOTE: In a full blown 3d system we would more formally define a Vector and a Matrix classto perform more robust 3d mathematics, and if we were going to do that then we might aswell just use WebGL (or equivalent)… but thats not really the point of this project. Ireally wanted to stick to old-school ‘just-enough’ pseudo-3d to build an outrun-style game.

Some More Trigonometry

One last piece of the puzzle is how to calculate d - the distance from the camera to theprojection plane.

Instead of hard coding a value for d, its more useful to derive it from the desiredvertical field of view. This way we can choose to ‘zoom’ the camera if needed.

Assuming we are projecting onto a normalized projection plane, with coordinatesfrom -1 to +1, we can calculate d as follows:

d = 1/tan(fov/2)

Setting up fov as one (of many) variables we will be able to tweak in order to finetune the rendering algorithm.

Javascript Code Structure

I mentioned in the introduction that this code does not exactlyfollow javascript best practices - its a quick and dirty demo with simple global variables andfunctions. However, since I am going to build 4 separate versions (straights, curves, hills and sprites)I will keep some re-usable methods inside common.js within the following modules:

  • Dom - a few minor DOM helpers.
  • Util - generic utilities, mostly math helpers.
  • Game - generic game helpers such as an image loader and the game loop.
  • Render - canvas rendering helpers.

I will only be detailing methods from common.js if they are relevent to the actual game, ratherthan just simple DOM or math helpers. Hopefully you can tell from the name and context what themethods are supposed to do.

As usual, the source code is the final documentation.

Program Car Race Game Opengl Source Code

A Simple Game Loop

Before we can render anything, we need a game loop. If you’ve followed any of my previousgame articles (pong, breakout,tetris, snakes orboulderdash) then you’ll have already seenexamples of my favorite fixed time stepgame loop.

Program

I won’t go into much detail here, I’ll simply re-use some of the code from my previousgames to come up with a fixed time step game loop usingrequestAnimationFrame

The idea being that each of my 4 examples can call Game.run(...) and provide their own versions of

  • update - the game world with a fixed time step.
  • render - the game world whenever the browser allows.

Again, this is a rehash of ideas from my previous canvas games, so if you need clarification on how thegame loop works go back and read those earlier articles (or post a comment below!).

Images and Sprites

Before our game loop starts, we load 2 separate sprite sheets:

  • background - 3 parallax layers for sky, hills and trees
  • sprites - the car sprites (plus trees and billboards to add to the final version)

The spritesheet was generated with a small Rake task using the sprite-factory Ruby Gem.This task generates the unified sprite sheets as well as the x,y,w,h coordinates tobe stored in the BACKGROUND and SPRITES constants.

NOTE: The backgrounds are home-made using Inkscape, while most of the sprites areplaceholder graphics borrowed from the old genesisversion of outrun and used here as teaching examples. If there are any pixel artistsout there who want to provide original art to turn this into a real game please get in touch!

Game Variables

In addition to our background and sprite images we will need a number of game variables, including:

Some of these can be adjusted using the tweak UI controls to allow you tovary some of the critical values at run-time to see what effect they have on therendered road. Others are derived from the tweakable UI values and recalculatedduring the reset() method.

Driving a Ferrari

We provide a key mapping to Game.run that allows for simple keyboardinput that sets or clears variables to indicate any action the playeris currently taking:

The variables that manage the player’s state are:

  • speed - the current speed.
  • position - the current Z position down the track. Note this is actually the position of the camera, not the ferrari.
  • playerX - the current X position across the road. Normalized from -1 to +1 to be independent of the actual roadWidth.

These variables are set within the update method, which will:

  • update position based on current speed.
  • update playerX if left or right arrow keys are pressed.
  • accelerate speed if up arrow is pressed.
  • decelerate speed if down arrow is pressed.
  • decelerate speed if neither up or down arrows are pressed.
  • decelerate speed if playerX is off the sides of the road and into the grass.

For straight roads, the update method is pretty clean and simple:

Don’t worry, it will get much more complicated when we add sprites andcollision detection in the final version :-)

Road Geometry

Before we can render our game world, we need to build up our array ofroad segments within the resetRoad() method.

Each of these road segments will eventually be projected from their world coordinatesto become a 2d polygon in screen coordinates. We store 2 points for each segment, p1is the center of the edge closest to the camera, while p2 is the center of the edgefarthest from the camera.

Technically, each segments p2 is identical to the previous sections p1 but wewill find it easier to maintain them as separate points and transform each segmentindependently.

The reason we maintain a separate rumbleLength is so that we can have fine detailedcurves and hills but still have long rumble strips. If each alternating segment wasa different color it would create a bad strobe effect. So we want lots of smallsegments, but group them together to form each rumble strip.

We initialize p1 and p2 with only z world coordinates because we only needstraight roads. The y coordinates will always be 0, while the x coordinateswill always be based on a scaled +/- roadWidth. This will change later when weadd curves and hills.

We also setup empty objects to store the camera and screen representationsof these points to avoid creating lots of temporary objects during every render

  • trying to keep our garbage collection to a minimum we want to avoid allocatingobjects inside our game loop whenever possible.

When the car reaches the end of the road we will simply loop back to the beginning. Tomake this a little easier we provide a method to find the segment for any Z value evenif it extends beyond the length of the road:

Rending the Background

Our render() method starts with drawing a background image. In future articles when we add curvesand hills we will want the background to parallax scroll, so we start off in that direction here byrendering the background as 3 seperate layers:

Program car race game opengl source code list

Rending the Road

The render function then iterates over the segments, and projects each segment’sp1 and p2 from world coordinates to screen coordinates, clippingthe segment if necessary, otherwise rendering it:


We saw the math required to project a point earlier, the javascript version combinesthe translation, projection and scaling equations into a single method:


In addition to calculating screen x and y for each of our p1 and p2points we also use the same projection math to calculate the projected width (w)of the segment.

Given the screen x and y coordinates for both p1 and p2, along withthe projected road width w, it becomes fairly straight forward for theRender.segment helper to calculate all the polygons it needs to render thegrass, road, rumble strips and lane separators using a generic Render.polygonhelper (see common.js)

Rendering the Car

Program car race game opengl source code download

Finally, the last thing required by the render method is to render the ferrari:

The reason this method is named player instead of car is because our finalversion of the game has other cars on the road, and we want to specificallydifferentiate the player’s ferrari from the other cars.

The Render.player helper ultimately uses the canvas drawImage method torender a sprite after scaling it based on the same projection scaling we sawearlier:

d/z

Where z in this case is the relative distance of the car from the camera storedin the playerZ variable.

Program Car Race Game Opengl Source Code Free

It also ‘bounces’ the car a little at higher speeds by adding a little random-nessto the scaling equation based on speed/maxSpeed.

And boom there you have it:

Conclusion

Thats actually a fairly large chunk of work already just to get us setup withstraight roads. We added…

  • a common Dom helper module
  • a common Util math helper module
  • a common Render canvas helper module…
  • … including Render.segment, Render.polygon and Render.sprite
  • a fixed step game loop
  • an image loader
  • a keyboard handler
  • a parallax layered background
  • a spritesheet full of cars, trees and billboards
  • some rudimentary road geometry
  • an update() method to drive a car
  • a render() method to render background, road and player car
  • an HTML5 <audio> tag with some racing music (a hidden bonus!)

… but it gives us a good foundation to build on. The next 2 articles, describingcurves and hillsshould be a little easier going, before getting more complex in the last article wherewe add sprites and collision detection.

Program Car Race Game Opengl Source Code Download

Related Links

Program Car Race Game Opengl Source Code List

  • read more about v1 - straight roads
  • read more about v2 - curves
  • read more about v3 - hills
  • read more about v4 - final
  • read Lou’s Pseudo 3d Page
  • view the source code

Program Car Race Game Opengl Source Codes

or you can play…

  • the straight road demo
  • the curves demo
  • the hills demo
  • the final version
Search
Code Directory
ASP
ASP.NET
C/C++
CFML
CGI/PERL
Delphi
Development
Flash
HTML
Java
JavaScript
Pascal
PHP
Python
SQL
Tools
Visual Basic & VB.NET
XML
New Code
OrgChart JS 7.6.13
EXE Stealth Protector 4.26
EXE Bundle - The file joiner 3.15
Flowrigami 1.0.1
Database Workbench Pro 5.7.8.353
IP2Location Geolocation Database Feb.2021
The C# Excel Library 2020.12.2
The C# Barcode Library 2020.12.2
Vue Injector 3.3.1
The C# OCR Library 2020.11
SentiVeillance SDK Trial 7.3.2020.11.30
VaxVoIP WebPhone SDK 4.0.6.0
SentiMask SDK Trial 2.0_193121
C# QR Code Generator 2020.12
How to Read Text from an Image in C# 2020.12
Top Code
Uber Clone with Safety Measure Addons 2.0
Answers phpSoftPro 3.12
phpEnter 5.1.
Quick Maps For Dynamics CRM 3.1
Single Leg MLM 1.2.1
Azizi search engine script PHP 4.1.10
Paste phpSoftPro 1.4.1
Extreme Injector 3.7
Apphitect Airbnb Clone Script 1.0
Deals and Discounts Website Script 1.0.2
Pro MLM 1
Solid File System OS edition 5.1
Classified Ad Lister 1.0
Aglowsoft SQL Query Tools 8.2
ICPennyBid Penny Auction Script 4.0
Top Search
Shop Asp
Yahoo Finance Php Stock
Cache Simulator C Code Download
Dirty Word
Master Page Template And Code
Code To Add Url
Connect Four Game Pseudocode
Photo Add Comment Php
Source Code To Read Video Files In Java
File Upload With Aspnet Codeproject
Srs For Online Art Gallery
Php Link Directory
Php Popup Alert
Autopilot Farming
Photo Gallery Comment Php
Related Search
Source Code For Car Racing In Opengl
Free Source Code For Car Racing In C
Source Code For Car Racing Games In Opengl
Source Code For Car Racing Games In Java
Source Code For Car Racing Games In Slash
Can I Have Source Code For Simple Games In Opengl
Chess Source Code For Computer Graphics In Opengl
Source Code For Snake Game In Opengl
Source Code For Graphics Project In Opengl
Free Source Code For Graphics Project In Opengl
Source Code For Memory Game In Opengl
Free Source Code For Car Game In C
Source Code For Random Movement In Opengl
Source Code For Car Racing Game
Free Source Code For Car Racing Game
Source Code For Car Racing In Opengl

Code 1-20 of 60 Pages: Go to 1 23Next >> page

Ledger Accounting for Firebird/Interbase - Ledger Accounting Software

Accounting source code for Delphi. Databases supported are Firebird 1.5 and Interbase 6.5. Reportbuilder is used for the report engine. Reasonably priced for C/S! Multiple currency, GL, AP, AR, Job Costing and Inventory. More features planned for 2005!

Python / Miscellaneous


This recipe will let you embed GIF images inside of your source code
for use in Tkinter buttons, labels, etc. It's really handy for making
toolbars, etc. without worrying about having the right icon files
installed.
The...

Development / User Interfaces


VIXEN is a Graphical Development Environment, written in XBLite, that generates the XBLite source code for the skeleton of a Windows GUI application.

Development / Documentation


Kelp is a source code annotation framework. Written in strict ISO C90 with support for Posix and Windows environments. Large file support. Supports both 32 and 64 bit platforms. Plugins for Vim and Eclipse are available.

Tools / Code Generators


Generates the C source code for Query Object Framework objects and provides a test environment linked against QOF to query objects, store in XML and export into SQL files. Create the fundamental object code from XML exported by any other QOF project.

Tools / Code Generators


rdb2oo is a project to create source code for classes which correspond to tables in a relational database.rdb2oo is also about creating an object oriented abstraction layer for simple database access.

Tools / Code Generators


gensrc - a Python application which takes XML descriptions of functions defined in a library and generates source code for addins on supported platforms including Microsoft Excel and OpenOffice.org Calc.

Tools / Code Generators


srcgen - a Python application which takes XML descriptions of functions defined in a library and generates source code for addins on supported platforms including Microsoft Excel and OpenOffice.org Calc.

Development / Frameworks


This project is the source code for the article Java in 7 steps. This article shows how to develop CRUD applications for the Web using the best of JEE technology and the simplest way to training the team.

ASP / Customer Support


Buy the ASP source code for the most comprehensive and portable, web based Help Desk System on the market. Automatic responses, notifications, and auto-customer matching put Help Centric in a league of its own. Includes separate applications for...

Tools / Development Tools


Ruby bindings for GLFW library, which is designed as replacement for GLUT toolkit in OpenGL. Intended to be used along with ruby-opengl.

Tools / Code Generators


Open QUB is a tool where developers easily can create user interfaces and generate source code for the UIQ 2.1 platform (running Symbian OS). The tool is developed in Java. Version 1.00 of Open QUB is, however, only system tested for the Windows...

Tools / Code Generators


MockMaker is a program for automatically creating source code for mock object. MockObjects can be used in automated Unit testing. See also www.Junit.org and www.mockobjects.com

Development / Frameworks


A library of re-usable source code for PureBasic.
Each library has been designed with cross-platform use in mind, and is standardised.

Blind Reverberation Time Estimation 1.0 - Marco Jeub


Matlab source code for blind reverberation time estimation from reverberant speech signals
The algorithm allows to estimate the reverberation time (RT or T60) within a range of 0.2s to 1.2s and assumes that source and receiver are not within...

Development / Front Ends


JadeTower's SourceForge project hosts source code for tutorials featured at http://www.jadetower.org

Inventory Management In VB.Net Demo 1.0 - Inventory-23


This is Demo Software only
The Full Source Code Also available
See for more detail and For Source Code
For Source Code Visit
http://www.inventoryinvbdotnet.com

Development / Modeling


Source code for sub-projects of Grid D&amp;D development team from SPbSU, Russia. Team focuses on the development of service-oriented grid software development for various applications in computer science as well as infrastructural components...

How to display records from top 4... - StarDeveloper


In this article the author shows how to set connections to database software. The author proceeds this task with DSN connections and DSN Less connections. The article provides the sample source code for these connections in SQL Server, ORACLE, MS...

Python / Miscellaneous


This recipe talks about how to implement rubberbanding code for canvas
objects in a wxPython application. Canvas classes in wxPython include
wxPanel, wxStaticBitmap, wxGlCanvas etc.

Home|Submit Code|Submit URL|Top Code Search|Last Code Search|Privacy Policy|Link to Us|Contact