Simple camera question -- follow rotation of object

How can I get my camera to follow this object’s rotation (about y) as well as position?

[19942-screen+shot+2013-12-30+at+22.51.45.png|19942]

19943-5seo6.gif

The object is three cylinders (two wheels and an axle) connected by joints. All three cylinders are children of an empty parent Gameobject called ‘Segway’. Intuitively, the orientation of the object is the orientation of the axle (ignoring the fact that it’s spinning).

The problem with making the camera a child of Segway is that Segway’s rotation doesn’t change when the compound object it contains rolls around. The problem with making the camera a child of one of the cylinders (wheel or axle) is that the cylinders rotate like crazy.

I’m going to assume that the axle is constructed from a cylinder and therefore the Transform.up of the axle will be along the axis of the cylinder. With that assertion, here is a bit of code that will cause the camera to follow and rotate to the axle:

#pragma strict

public var axle : Transform;
public var camHeight = 2.0;
public var camDist = 4.0;
 
function LateUpdate() {
	var v = Vector3.Cross(axle.up, Vector3.up) * camDist;
	v.y += camHeight;
	transform.position = axle.position + v;
	transform.LookAt(axel);
}

‘camDist’ is the distance behind the axle to follow. ‘camHeight’ is the height to place the camera above the axle. You will need to initialize ‘axle’ either by dragging and dropping in the Inspector, or you can use something like GameObject.Find() or GameObject.FindWithTag() in the Start() to initialize the variable. I may have the two parameters in the Vector3.Cross() reversed.