Rotating following camera for a sphere

I’m new to unity and I’m trying to get the hang of it, I’m following this tutorial http://unity3d.com/learn/tutorials/projects/roll-a-ball to try and create movable ball similar to monkey ball. I’ve created a camera that is following the sphere using this code:

public class PlayerFollow : MonoBehaviour {
	public GameObject Marble;
	private Vector3 offset;
	// Use this for initialization
	void Start () {
		offset = transform.position;
		Debug.Log (offset);
	
	}
	
	// Update is called once per frame
	void LateUpdate () {
		transform.position = Marble.transform.position + offset;
	}
}

While this works correctly and follows the sphere, I am unsure how to make it so the camera rotates when the user moves the ball eg. when user moves backwards the camera rotates around to show user the objects behind him.

Also if anyone has any sites to get me started that would be nice of you.

Thanks

You move and rotate the camera using its transform. I usually find it’s simplest to do this by managing two points in space:

So, in your case, we might do something like this:

  • The camera is located at the player (with some offset)
  • The camera looks in the same direction as the player

In code:

transform.position = Marble.transform.position + offset;
transform.LookAt(Marble.transform.position - offset);

You could apply a separate offset, but that should give you the rough idea.

Your next question is probably: how do I get the camera to look around more smoothly? That can get pretty complicated, but in general:

  • Where is the camera looking, right now?
  • Where should the camera be looking, ideally?

During each frame, the first point should move just a little bit closer to the second.

Something like this, maybe:

//assumes you have two variables, lastLookPoint and targetLookPoint
Vector3 currentLookPoint = Vector3.MoveTowards(lastLookPoint, targetLookPoint, 5 * Time.deltaTime);
transform.LookAt(currentLookPoint);
lastLookPoint = currentLookPoint;

All of these are just suggestions. Ultimately, all you need to do is translate and rotate the camera. You’re free to do that in any way you can design and build.

I’m in the exact same boat, I am still working on it, like if I leave the first part transform.position = Marble.transform.position + offset;

in the code the camera does not change at all and just follows from same view.
when I take that part out, the camera will use the “lookat” code and actually change direction and rotation but it will not move… for obvious reasons.

I believe I need to setup “if” statements that detects if player is traveling along the x axis or the z axis and have the camera stay the same offset except from a different angle.

example: marble goes left and camera stays same distance however moves to be behind marble instead of side view