Monday, May 16, 2011

3D car with a camera that follows it

Ever wondered how to build a simple 3D car movement with camera that follows the car?
Let’s have at this tutorial, which uses Alternativa 3D 8 (Molehill).

Download Alternativa 3D 8.

This tutorial consist of these parts:
- move a car with keyboard controls
- follow the car with a camera

The final app will look like this:
Molehill Car With Follow Camera
(*requires Flash Player with Molehill)

To understand the car’s movement let’s do a little bit of math.

Speed / Acceleration

When we press UP key, we add acceleration to the speed. When DOWN key, we subtract acceleration from the speed. When none of them is pressed, we slow down by multiplying actual speed by 0.96 – note it can be whatever, depends on how fast or slow you want to slow down.

// don't allow to speed up more than maximum speed
if (accelerate && speed<speedMax) {
 speed+=2;
}else if (brake) {
 speed-=2;
}else{
        // When the speed is below 0.3 threshold, 
        // we pass 0 to stop the car
        // and avoid little unwanted movements.
 if (Math.abs(speed)>0.3) {
  speed*=0.96;
 } else {
  speed=0;
 }
}

Steering / Rotation

When we press LEFT or RIGHT key, we turn the car by Math.PI/40 radians (4.5 degrees). Again, pass number that fits you best.

[...]

Read more: 3D car with a camera that follows it

No comments:

Post a Comment