Thursday, 26 April 2007

Explosions and Fireworks

Explosions and Particle Animation

Explosions are common in games. In this workshop you will develop an applet which demonstrates simple fireworks as an example of an explosion.

An explosion (and a firework being no exception) involves a high number of small objects called particles, moving very fast. In computer animation the proper technique applied here is called particle animation and in fact is one of the most common animation techniques. Small objects are controlled using some rather elementary physics; good results are obtained mostly thanks to the really high number of particles involved than any complexity of a single object. So, we can think about particles as very simple physics-based objects that reveal their power when act in a large flock. Besides explosions, the technique is commonly used to model smoke, fog, fire and even water, depending on appearance and behaviour of the particles.

Fireworks: a Very Simple Model

First, a payload is shot to some altitude; often the payload is a rocket to get higher altitudes. As this initial stage is just a flight, and not an explosion, we will ignore it and start our simulation from the moment when the payload is fired and explodes into a plethora of particles. In the most classical type of fireworks these particles are distributed evenly in all directions, forming a quickly expanding sphere. The particles concentrate near the surface of this sphere. Seen from a distance, particles simply seem to fly with diverse velocity: the highest in case of those flying perpendicular to your optical axis, and the lowest in case of those flying along the axis. A very simplified model can therefore assume particles flying from a designated point on a 2D cast surface with random velocity.

Initial Implementation

Please download Kingston University Games Fundamental Classes (see the link on the right). Be careful not to overwrite anything valuable when unpacking the archive. Instead you can download this to get only the files involved in this project. The applet is a framework solution based on simplified and somewhat naive assumptions listed below:

  • There is just one firing, executed at the start-up of the program
  • All particles start from the centre of the window, i.e. point (400, 300)
  • All particles are of the same size (2)
  • The colour hue of the particles is random
  • 500 particles are created
  • All of them immediately start to travel with a random velocity and in a random direction.

See FireworksGame.onStart function, where the particles are created.

The FireworksGame class incorporates a list of particles and also controls their updating and drawing. Any particle added to m_particles will be properly processed.

The Particle class incorporates a simple color scheme in which you can separately set the hue and the brightness (this is HSB or Hue-Saturation-Brightness colour scheme, used as an option in most serious graphical packages). This allows for simple controlling of the brightness of a particle.

Run the program, observe, think why the overall look-and-feel is far from satisfactory.

Getting a better geometrical model

What is wrong, is the distribution of velocities of our particles. The model applied in the first, naive solution assumes that all the observed velocities have the same probability. It is not true. There is just a small fraction of particles flying straight towards you or straight away of you (along the optical axis). However there is significantly more of them flying to the sides, perpendicualar to the axis; they create a visible front, or a circular wave, which makes the cloud of particles looking spherical. Relatively more particles should therefore get higher velocities and less of them - lower. Without this, instead of an elegant "expanding sphere" effect, what we get is a just shapeless flock of flying elements.

Tasks to do:

Task for everyone:

  • Find out what should be the distribution of (random) velocity of the particles to get a natural look and feel and apply it (see FireworksGame.onUpdate function where the velocity is calculated).

Hint: The surface area of a spherical dome's ceiling is 2 pi r h, where r is the sphere radius and h is the position of the dome's cutting plane...

Tasks to choose (do as many as you can):

  • Change the place where the fireworks are fired from the centre of the window to a random position (very easy)
  • Change the program so that to get a series of explosions instead of a just one (easy)
  • Apply various (random) sizes of particles (very easy)
  • Update particles so that they fade after a time (easy)
  • Play with the previous task, try out several non-linear modes in which they may fade (medium)
  • Update particles so that they shrink after a time (medium)
  • Add gravitation: particles not only fly, but also slowly fall down (medium)
  • Delete the particles from the particle list when they are no longer visible (medium)
  • Change the shape and kind of fireworks (difficult)
  • Show particle traces - a recent part of trajectory glows forming a "tail" (difficult)
  • Add secondary explosions: after a time the particles may explode once again (difficult)
  • Add rotational motion (particles flying along spiral trajectories) (very difficult)

Thursday, 29 March 2007

Cars

During this workshop you will play with the mechanics of cars. You will also learn how to implement simple physics-based engine.

Prerequisites

First, please download the following image of a car. Click with a right button of your mouse and choose Save Picture as...
Please save the image where you have all the java games images (depending on the version, it may be the main Games folder or Games/images subfolder).

Below is the list of the source files that you need. You can write them yourself, create them working along with the Tutor, or simply download them. In all cases please use the Create New Package button in your eclipse to create a new package named Cars and ensure all the source files are created/stored within this package. The package home folder on the disk is in your eclipse Workplace, Games/kingston/games/cars.

This is the list of source files:
  • Cars.java - start-up class. Once created, you probably will have no need to modify it.
  • CarsGame.java - the main game class.
  • Car.java - the Car Sprite class.

CarsGame Class

This is the main class of this game. If you downloaded its file, you probably won't need any corrections to be done, as the version here available is enough functional to go through this exercise. Still you may want to know what this class does.

Summary of variables:

  • imageCar - contains a bitmap with the image of the car
  • car - reference to the Car object

Summary of functions:

  • onStart: loads the image of a car and create a Car class object - the car Sprite.
  • onUpdate: updates the state of the Car object - delegates this task to Car.onUpdate
  • onDraw: draws the playfield, namely the Car object on top of a large white rectangle.
  • onTerminate: does nothing.
  • keyPressed: this function is called whenever the user presses any key. It checks ESC and ^C keys to exit the game; F2 to start the game anew; RIGHT/LEFT arrows to control turning; UP/DOWN arrows for forward/reverse gears; SPACE for brakes.
  • keyReleased: this function is called whenever the user releases a key and switches off the key-related functions.
  • newGame: this function is called whenever the game is started anew after pressing F2. The function simply destroys the old car object and creates a new one.

Car Class

This class encapsulates entire functionality of the car and extends the Sprite class. It controls the your car look and behaviour.

Summary of variables:

  • turn: see turn function below.
  • accel: see accelerate function below.
  • brakes: see brake function below.

Summary of functions:

  • turn: call turn(-1) to turn left, turn(1) to turn right or turn(0) to drive straight on.
  • accelerate: call accelerate(1) for forward gear, accelerate(-1) for reverse gear, or accelerate(0) for neutral.
  • brake: call brake(true) to switch the breaks on and brake(false) to switch them off.
  • onUpdate: see the next section below...

Your task to do

Depending on:

  • the gear (forward, reverse or neutral),
  • the turning (left, right or straight on) and
  • the brakes (on or off)

please implement the physically realistic behaviour of a car. Your implementation should be placed within the Car.onUpdate function.

Hints:

  1. Depending on the gear, determine the acceleration. Reverse acceleration should be around 3-5 times lower than the forward one.
  2. Calculate air resistance as a multiple of the square of your velocity.
  3. Use fixed value for the rolling resistance.
  4. Brakes are another form of resistance. Apply only when brakes are on!
  5. Modify your velocity. In general, velocity = (previous) velocity + acceleration * time elapsed. Be careful about the resistances: they always should decrease the absolute value of the velocity.
  6. Finally use the turn value. You can turn left or right adding or subtracting very small values from the direction and rotation of your car.

Index of useful classes available within your Sprite/Car object:

  • getMyTime - time elapsed since previous update.
  • getVelocity, setVelocity - numerical value of velocity.
  • getDirection, setDirection - direction of the motion (vector or velocity)
  • getRotation, setRotation - rotation of the sprite.

Wednesday, 28 March 2007

Coursework - how to submit?

In-class presentations: Friday 30 March
Submissions due to: Monday 2 April


This submission may be an intermediary project development report. This means that your game does not have to be finished. It is however absolutely essential to submit this report before the deadline.

The projects must be finished before the 2nd Coursework deadline which is 8 May.

Notice that, as a result of numerous demands, 2D games will be accepted in the 1st assessment under the condition some other advanced mathematical concept is demonstrated within your application. Still 3D (billboard-based) solutions have better chances to earn good marks.

In-class Presentation

This submission will reflect the current development stage. Therefore it should clearly state:

  • what was already done
  • what is the current state of the project
  • what is planned to do.

If you are not ready with your project and you are preparing a presentation for Friday, just focus on those three points. Try to explain what you have found difficult in your implementation and if it is possible, try to locate particular problems that made you late (or even stuck) with the project. While presenting, try to show your best achievements so far. It's good to demonstrate any working piece of software. If you for example are planning to create a space shooter game and you have already implemented your spacecraft and its steering, show it. You don't have to show enemy ships if they're not ready, and you don't have to show how you shoot if you can't. However a good idea would be to spend some extra time on filling the space with the stars - technically, the problem is relatively simple, but the effects may be visually stunning. Explain what your goal is - what your game is going to contain once it is finished. Supplying static images (mock-ups) would be great.

Of course your presentation is going to be much easier to prepare if you are ready with your project by now. It is just enough to show your game in action!

What should be done in the Written Report

Each information project comprises three basic steps, analysis, design and implementation, and not surprisingly computer games are not an exception. You are supposed to have already finalised the analysis of your project and also design should be outlined by now, however it is possible to introduce some corrections on the further stages. Your implementation does not have to be finished.

Your final report should contain following elements:

  • Game Concept (or idea) - what the game is about, what is its goal, what you think may be its highlight. You can supply scripts (i.e. screenplays), storyboards, a legend (an epic story behind the game), graphical designs etc.
  • Requirements. These are short sentences defining what is expected from a game. From simple things (e.g. the rocket shoots the asteroids, ball can reflect and bounce, car may turn left and right) to much more transcendental (e.g. vehicle should behave realistically when steered, the user should have a feeling like with a real thing). The requirements should cover all the functionality of the game - however in case of a small game they can be in most cases kept brief. NOTE: Requirements are strictly technical - use proper, precise language, keep them brief and informative, apply a bulleted list style to enumerate them.
  • Technical Analysis - what particular methods did you apply to model the in-game world. This is primarily where you are supposed to discuss the mathematical basis for your game, and possibly also physics standing behind.
  • Software specification - what classes have you planned to use, what variables do you use, what your functions do (especially onUpdate and onDraw should be precisely and clearly specified).
  • Sample screenshot / prototype / mock-up may be added if needed. If you decide to include this part, please keep it concise - submit just the essential things.

Your report is a technical text. Keep it simple, consistent and concise. Use clear formatting. Bulleted lists, figures, diagrams are always welcome. Explain every picture (add captions). Never write things that I already know. For example it is enough to say that you apply Newton's second law, don't write about this law. Don't document classes that are supplied to you - they're already documented. The only part of your report where you can play storytelling is the Game Concept - all the rest is a formal technical documentation, not an essay.

Good luck!

Friday, 9 March 2007

Ballistic Games

Please download the newest version of KU Fundamental Games Classes and look for the project called "Ballistic". Follow my life instructions.

Ballistic is an unfinished game that you are supposed to finish. You fire from two cannons (in turns) and the cannon balls should fly according to the laws of physics - that is obviously not the case at the current stage of development. Please do the following things:
  1. Apply laws of physics to model a realistic trajectory for the cannon balls.
  2. Detect when the ball hits the ground or a cannon, and also control the situation when the ball leaves the screen far above the ground.
  3. Calculate score for all the canons hits and change turns so that two players could play the game.

Most things are to be done within the CannonBall class. This is a Sprite subclass. It already draws itself (the onDraw function) and uses its default onUpdate behaviour to apply some generic motion. This motion is currently linear and infinite what obviously is not what we want to get.

Any object thrown has two velocity components. One of them, horizontal, is constant and is equal to the horizontal component at the moment of firing. According to Newton's 1st law this velocity does not change. Real objects subject to the air resistance and in fact their horizontal component is slightly delayed, but we will ignore this. Objects fall with acceleration of g=9.81 m/s2 (close to the Earth surface). If thrown, they also get some initial vertical component of velocity, that is constant. This initial velocity is gradually changed over the time. The general formula is:

v = v0 + gt

where v0 is the initial velocity (vertical), g is Earth acceleration and t is the time.
Notice that the sign of v0 may be different than that of g. In that case the acceleration first causes the motion to delay until it stops, and then a regular fall begins, until the object hits the ground!

You can use your ball Sprite to read all its current params including position, velocity and its componnents, etc. The array called silhouette contains a set of values defining the shape of the ground (that brown mountain) and therefore may be used to detect if the ball hits the ground. Lastly, you can use cannon[0] and cannon[1] to determine the position of the left and the right cannon, respectively.

Hint: CannonBall.onUpdate is a good place to put most of your code (why?)

Good luck!