# How to let a GameObject or Camera follow a path?

I want to let a vehicle or camera follow a path (stick to a line) that I defined in design time. (Like a train following a rail). The vehicle or camera would be operated by the user (press a key to go forward or another key to go backwards).

I really don't have any clue how to build something like this, and I can't find some tips to do something like this.

Can someone help me with this? Or can you give me some tips?

Thanks

Update: All solutions given here use splines which gives the wrong effect for me. I want to move, say a car, along a path in a straight line and at some point turn into a corner (the path would be straight followed by a quarter of a circle, followed by a straight line again.)

You might be able to use something like spline controller from the UnifyCommunity wiki,

There are numerous options, but if you want to keep coding to absolute minimum, you could try to make an animation of a point in your 3D program, and in Unity attach the camera to the animated point and play the animation. Another option that doesn't require too much programming is AniMate.

I think this website have the script you are looking for: (but it is in french) http://www.unity3d-france.com/unity/?p=105

Here is a camera following a line created with Blender (or 3D equivalent.) It is not controllable but this may be the "base" script that you need. Full project file included. http://forum.unity3d.com/threads/5438-Camera-path-technique

For the line, you simply need to point the camera in the correct direction (use the equation of a line) and Translate(0,0,X). For the quarter circle, use the equation of a circle. What you want is a circle (x^2 + z^2 = r^2) that is not centered on the origin (your camera's starting location), but has the position of the camera on the circle itself at (0,0) with the circle's center at (-r,0), ignoring the y for the moment. (which will then follow 1/4 of the circle until it has made its turn). So basically you want to calculate your x position as a function of z:

if r = radius of circle, and z goes from 0 to r ... one-quarter of a circle, the distance of the radius from the origin... then you can plot the position as:

x = (r^2 - z^2) - r

That will plot out a quarter circle path for you. Then you simply need to position your camera at (x, constant, z) for each z from 0 to r.

To change the direction of the camera, use theta = z/r*90, then Rotate from the original angle (0, theta, 0).

This will allow you know the exact position and angle of the camera at every step along your path and quarter circle. Just remember to store your original coordinates (before the start of the turn) and reset to those each time before you position and rotate.

Make an animation and use key frames like flash : Unity 3D: Introduction to Animation - YouTube

If you need a little more control than the Unify example, you might want to check out my asset Camera Path