Move GameObject along a line according to the players look direction

I have two GameObjects: The Main Camera, which the player can rotate, and a box, which only moves in the z-axis. I need the box to always be in the Main Camera’s forward position, and newer move away from it’s line.

I’ve tried to illustrate it:

Additional information: I’m coding in C# and have tried different solutions with vectors, but just can’t get my head around a solution.

you can use a ray cast hitting an invisible collier which will act as your line and place the gameObject at the raycast contact point.

see: http://unity3d.com/support/documentation/ScriptReference/RaycastHit-point.html
and: http://unity3d.com/support/documentation/ScriptReference/RaycastHit.html

for help

You can also use the Plane object so you have an infinite large “collider” plane.

A mathematical plane is defined by it’s normal vector and the distance from 0,0,0. You can create a plane be hand in the normal vector to define in which direction the plane should face and any point in world coordinates that is on the plane:

private Plane m_Plane;

void Start()
{
    // This plane will be at 0,0,20 and face towards the origin(0,0,0)
    m_Plane = new Plane(-Vector3.forward, new Vector3(0,0,20));
}

//[...]
Ray ray = Camera.main.ViewportPointToRay (new Vector3(0.5,0.5,0));
float dist;
if (m_Plane.Raycast(ray, out dist))
{
    Vector3 hitPoint = ray.GetPoint(dist);
    // use it
}

The plane object isn’t a visual component. It’s just the mathematical representation of a plane.

Just use the camera transforms forward direction and zero out the y axis. that’s important because the camera always “looks down” on the player, but you don’t want to move in that direction (cause you’d go through the ground :P)

Vector3 forward = Camera.main.transform.foward;
forward.y = 0f;    
// Move the box    
transform.Translate(forward * speed * Time.deltaTime);